[英]converting string to hex
I have a string that has 0111111100000000000000000000101 我有一个具有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. 但是当我打印它时,它的输出为101。我认为sscanf可以从字符串转换为十六进制,这是我做错了什么以及如何解决。 The result I want is 0x3F800005
我想要的结果是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. 您的
sscanf
将字符串读取为HEX,但该字符串以二进制形式编写。 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
. 您将得到“ 101”,因为
int
只能存储前8位-每个数字为4位,因此两位= 8位= 1个字节,而8位为4个字节,这是int
的大小。 So you actually store "00000101", buy printf
does not print the leading zeroes so you get "101". 因此,您实际上存储了“ 00000101”,购买
printf
不会打印前导零,因此您会得到“ 101”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.