// msvc 17.3.5
// sizeof (long) : 4
#include <stdlib.h>
int main(){
long i = 0xAABBCCDD;// 0x AABBCCDD in debugger window
char number[] = "AABBCCDD EEFF";
char* p;
long var = strtol ( number, &p, 16 );// 0x 7FFF FFFF
perror ( "?:" ); // ?:: Result too large
}
I tried char number[] = "AABBCC EEFF"; and it works fine.
I expect 0xAABBCCDD inside var instead 0x7fffffff.
What is wrong?
From the C Standard (7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions)
The positive hexadecimal constant
0xAABBCCDDcan not be represented in an object of the signed typelong intprovided thatsizeof( long int )is equal to4.For example try this demonstration program
The program output is
Note: as in this case
sizeof( long )is equal tosizeof( unsigned int )and the value is representable in an object of the typeunsigned intthere is used the conversion specifierX. Otherwise you need to include header<inttypes.h>and to use a macro as for examplePRIX32.As you can see
LONG_MAX(the maximum positive value that can be stored in an object of the typelong int) is less than the positive hexadecimal constant0xAABBCCDD.Instead of using the function
strtoluse functionstrtoulOr if you want to deal with signed integers then use function
strtoll.