C 中的十六进制到十进制转换

发布于 2024-08-27 11:28:44 字数 593 浏览 2 评论 0原文

这是我的代码,它正在执行从十六进制到十进制的转换。十六进制值存储在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生生漫 2024-09-03 11:28:44

根据您对 %x 的使用,我的猜测是 content 将您的十六进制数字编码为整数数组,而不是字符数组。也就是说,您是否将 content 中的 0 数字表示为 '\0' 还是 '0'

strtol 仅适用于后一种情况。如果 content 确实是一个整数数组,则以下代码应该可以解决问题:

hexToDec = 0;
int place = 1;
for(int i=3; i>=0; --i)
{
  hexToDec += place * (unsigned int)*(content+i);
  place *= 16;
}
content += 4;

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 in content as '\0', or '0'?

strtol only works in the latter case. If content is indeed an array of integers, the following code should do the trick:

hexToDec = 0;
int place = 1;
for(int i=3; i>=0; --i)
{
  hexToDec += place * (unsigned int)*(content+i);
  place *= 16;
}
content += 4;
香草可樂 2024-09-03 11:28:44

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文