Conversion of strings into numbers and precautions
Convert a string to a number:
Atoi, atol, and atoll are required for Signed Conversion. Use strtoul and strtoull for unsigned conversion.
(1) Common conversion functions
Converted to signed:
# Include
Int atoi (cosnt char * nptr );
Long atol (const char * nptr );
Long atoll (const char * nptr );
Long atoq (const char * nptr );
Long int strtol (const char * nptr, const char ** endptr, int base );
Long int strtoll (const char * nptr, char ** endptr, int base );
Converted to unsigned:
Unsigned long int strtoul (const char * nptr, char ** endptr, int base );
Unsigned long int strtoull (const char * nptr, char ** endptr, int base );
(2) scenario Problems
Unsigned int value = (unsigned int) atoi (3000000000 );
Printf (value = % u, value );
In a 64-bit machine, value = 3000000000. However, in 32-bit machines, value = 2147483647
Because the atoi function is implemented using strtol internally, in atoi, strtol converts 3000000000 to the long type first,
In 64-bit machines, long is 8 bytes, the highest bit is the symbol bit, and the data bit is 63 bytes.
In 32-bit machines, long is 4 bytes, the highest byte is the symbol bit, and the data bit is 31 bytes. The strtol function truncates 3000000000 to 2147483647 (the maximum number of four-byte positive values, that is, the number of binary data is 0111 1111 1111 1111 1111 1111 1111 1111 ).
Use strtoul to correctly handle the error (valid for the number of 4-byte unsigned characters ).
Similarly, for 8-byte unsigned numbers, strtoull is required. Otherwise, even if atoll is used for conversion, the same problem may occur (either 64-bit or 32-bit ).
The Code is as follows:
Example
12345678910111213141516
|
/* Strtoull example */# Include
/* Printf, NULL */# Include
/* Strtoull */IntMain (){CharSzNumbers [] =250068492 7b06af00 1100011011110101010001100000 0x6fffff;Char* PEnd;Unsigned Long Long IntUlli1, ulli2, ulli3, ulli4; ulli1 = strtoull (szNumbers, & pEnd, 10); // This number is a 10-digit number ulli2 = strtoull (pEnd, & pEnd, 16 ); // The hexadecimal number ulli3 = strtoull (pEnd, & pEnd, 2); // The hexadecimal number ulli4 = strtoull (pEnd, NULL, 0 ); // This number is based on the specified prefix's hexadecimal number printf (The decimal equivalents are: % llu, % llu, % llu and % llu., Ulli1, ulli2, ulli3, ulli4 );Return0 ;}
|
|
Output:
The decimal equivalents are: 250068492, 2064035584, 208622688 and 7340031. |