I have a string that has 0111111100000000000000000000101
I wanted to convert this to hex, so I used the code below
int assembledHex;
sscanf(buffer, "%x", &assembledHex);
printf("this is the assembled hex %x\n",assembledHex);
but when I print it, it gives me 101. I thought sscanf can convert to hex from a string, what am I doing wrong and how can I fix it. The result I want is 0x3F800005
This is not checked or anything, and also quite slow, but it's a quick start:
unsigned int bin_to_int(const char *s) {
int i;
unsigned int result;
result = 0;
if (s[0] == '1') result++;
for (i = 1; i < strlen(s); i++) {
result <<= 1;
if (s[i] == '1') {
result++;
}
}
return result;
}
Your sscanf
is reading the string as HEX, but the string is written in binary. You get "101" because int
can only store the first 8 digits - each digit is 4 bits, so two digits=8 bits=1 byte, and 8 digits are 4 bytes, which is the size of int
. So you actually store "00000101", buy printf
does not print the leading zeroes so you get "101".
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.