Last active
June 11, 2017 14:19
-
-
Save deltheil/7502883 to your computer and use it in GitHub Desktop.
C: character string to uint16_t conversion (see http://stackoverflow.com/q/20019786/1688185)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <inttypes.h> /* strtoumax */ | |
#include <stdbool.h> | |
#include <errno.h> | |
static bool str_to_uint16(const char *str, uint16_t *res); | |
int | |
main(int argc, char *argv[]) | |
{ | |
if (argc != 2) { | |
fprintf(stderr, "usage: %s <port>\n", argv[0]); | |
exit(1); | |
} | |
uint16_t port; | |
if (!str_to_uint16(argv[1], &port)) { | |
fprintf(stderr, "conversion error\n"); | |
exit(2); | |
} | |
printf("port: %" PRIu16 "\n", port); | |
return 0; | |
} | |
static bool | |
str_to_uint16(const char *str, uint16_t *res) | |
{ | |
char *end; | |
errno = 0; | |
intmax_t val = strtoimax(str, &end, 10); | |
if (errno == ERANGE || val < 0 || val > UINT16_MAX || end == str || *end != '\0') | |
return false; | |
*res = (uint16_t) val; | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment