简体   繁体   中英

Converting from long to hex in C?

I have this code

char binary[] = "0001001010000011";
long number = strtol(binary, NULL, 16);
printf("%x", number);

I want to convert the string into a hex number. the answer is 1283, but i am getting DF023BCF what am i doing wrong?

The base you specify to strtol is the base to use to parse the input , not the output (which instead is specified by the %x ). IOW, that code says to strtol to parse 0001001010000011 as if it were a hexadecimal number (and, by the way, it results in overflow).

The last parameter to strtol is the base that you want to convert from. Since you are providing a binary encoded string you should specify a base 2 conversion.

Here is the correct code:

char binary[] = "0001001010000011";
long number = strtol(binary, NULL, 2);
printf("%x", number);

I would also suggest that binary numbers are not normally signed (especially when 17 digits long), therefore, it seems likely that you may want to use the unsigned version of the function, strtoul() as shown below. Finally, when printf'ing a number into hex format it might be a good idea to indicate hexadecimal with a leading 0x marker. In your case, the answer is 0x1283 but displaying this number as 1283 allows it to be easily confused as a decimal number. Both suggestions are shown below.

const char binary[] = "0001001010000011";
unsigned long number = strtoul(binary, NULL, 2);
printf("0x%x", number);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM