Created
January 13, 2015 14:24
-
-
Save dsggregory/32899c4099ba77f22747 to your computer and use it in GitHub Desktop.
Supporting unsigned int string conversions without going negative
This file contains 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
/* NOTES: | |
1. On 64bit without stdlib.h included, atol and strtoul of >MAXINT | |
returns "18446744071562067968" which is ULONG_MAX-INT_MAX on 64bit | |
2. On 32bit | |
a. with or without stdlib, >MAXINT returns MAXINT for atol() | |
b. W/wo stdlib, strtoul does the correct conversion | |
SUGGESTIONS: | |
1. Build for 64bit but make sure stdlib.h is included | |
2. Example | |
#if __WORDSIZE == 64 | |
# include <stdlib.h> | |
#else | |
# define atol(x) strtoul(x, NULL, 10) | |
# define atoi(x) (unsigned int)strtoul(x, NULL, 10) | |
#endif | |
*/ | |
#include <stdio.h> | |
#if __WORDSIZE == 64 | |
# include <stdlib.h> | |
#else | |
# define atol(x) strtoul(x, NULL, 10) | |
# define atoi(x) (unsigned int)strtoul(x, NULL, 10) | |
#endif | |
#include <limits.h> | |
#define MAXINT_STR "2147483647" | |
#define MAXINT_PLUS_ONE_STR "2147483648" | |
#define ULONGMAX_PLUS_ONE_STR "" | |
int | |
main(void) | |
{ | |
unsigned int i = (unsigned int)atoi(MAXINT_PLUS_ONE_STR); | |
unsigned long l = (unsigned long)atol(MAXINT_PLUS_ONE_STR); | |
unsigned long sl = (unsigned long)strtoul(MAXINT_PLUS_ONE_STR, NULL, 10); | |
printf("MAXINT: %u\n", INT_MAX); | |
printf("ULONGMAX: %lu\n", ULONG_MAX); | |
printf("atoi: %u\n", i); | |
printf("atol: %lu\n", l); | |
printf("strtoul: %lu\n", sl); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment