[英]C - Convert Hex value to int and store in char array
I have the following code, 我有以下代码,
int main(){
const char *hexstring = "f";
int number = (int)strtoul(hexstring, NULL, 16);
printf("%d", number); //Prints 15
char s[5];
s[0] = number;
printf("%d", s[0]); //prints 15
}
I ran it for "1F" and it returns 31 as expected. 我为“ 1F”运行它,并按预期返回31。
if, hexString
value is FF or any other value which results in 3 digit number, s[0]
returns a negative value. 如果
hexString
值为FF或导致3位数字的任何其他值,则s[0]
返回负值。
What am i doing wrong? 我究竟做错了什么? How can i make
s[0]
hold 255 in case hexString
is "FF". 如果
hexString
为“ FF”,如何使s[0]
保持255。
char
can be signed or unsigned. char
可以签名或不签名。 It looks like char
is signed on your platform. 看起来
char
已在您的平台上签名。 In your case you want to use unsigned char
. 在您的情况下,您想使用
unsigned char
。
Change: 更改:
char s[5];
to: 至:
unsigned char s[5];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.