C 中的十六进制到十进制转换
这是我的代码,它正在执行从十六进制到十进制的转换。十六进制值存储在 unsigned char 数组中:
int liIndex ;
long hexToDec ;
unsigned char length[4];
for (liIndex = 0; liIndex < 4 ; liIndex++)
{
length[liIndex]= (unsigned char) *content;
printf("\n Hex value is %.2x", length[liIndex]);
content++;
}
hexToDec = strtol(length, NULL, 16);
每个数组元素包含 1 个字节的信息,我已读取 4 个字节。当我执行它时,这是我得到的输出:
Hex value is 00
Hex value is 00
Hex value is 00
Hex value is 01
Chunk length is 0
任何人都可以帮助我理解这里的错误吗?小数值应该显示为 1 而不是 0。
此致, 黑暗者
Here is my code which is doing the conversion from hex to decimal. The hex values are stored in a unsigned char array:
int liIndex ;
long hexToDec ;
unsigned char length[4];
for (liIndex = 0; liIndex < 4 ; liIndex++)
{
length[liIndex]= (unsigned char) *content;
printf("\n Hex value is %.2x", length[liIndex]);
content++;
}
hexToDec = strtol(length, NULL, 16);
Each array element contains 1 byte of information and I have read 4 bytes. When I execute it, here is the output that I get :
Hex value is 00
Hex value is 00
Hex value is 00
Hex value is 01
Chunk length is 0
Can any one please help me understand the error here. Th decimal value should have come out as 1 instead of 0.
Regards,
darkie
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您对 %x 的使用,我的猜测是
content
将您的十六进制数字编码为整数数组,而不是字符数组。也就是说,您是否将content
中的 0 数字表示为'\0'
还是'0'
?strtol
仅适用于后一种情况。如果content
确实是一个整数数组,则以下代码应该可以解决问题:My guess from your use of %x is that
content
is encoding your hexademical number as an array of integers, and not an array of characters. That is, are you representing a 0 digit incontent
as'\0'
, or'0'
?strtol
only works in the latter case. Ifcontent
is indeed an array of integers, the following code should do the trick:strtol
需要一个以零结尾的字符串。length[0] == '\0'
,因此 strtol 就在那里停止处理。它会转换“0A21”之类的内容,而不是像您这样的 {0,0,0,1} 之类的内容。content
的内容是什么?您到底想做什么?你所构建的东西在很多方面对我来说都很奇怪。strtol
is expecting a zero-terminated string.length[0] == '\0'
, and thus strtol stops processing right there. It converts things like "0A21", not things like {0,0,0,1} like you have.What are the contents of
content
and what are you trying to do, exactly? What you've built seems strange to me on a number of counts.