Skip to content

Instantly share code, notes, and snippets.

@deltheil
Last active June 11, 2017 14:19
Show Gist options
  • Save deltheil/7502883 to your computer and use it in GitHub Desktop.
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)
#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