在 C 中将存储为字符的十六进制字符串转换为十进制
我得到一个字符串 hex_txt,其中包含代码中概述的 4 位十六进制数字,分为两个数组条目。我需要将其转换为十进制。以下是我正在做的方法。
unsigned char hex_txt[] = "\xAB\xCD";
unsigned char hex_num[5];
unsigned int dec_num;
sprintf(hex_num, "%.2x%.2x", (int)hex_txt[0], (int)hex_txt[1]);
printf("%s\n", hex_num);
sscanf(hex_num, "%x", &dec_num);
printf("%d\n", dec_num);
有没有更快或更有效的方法来做到这一点?这是我当前的临时解决方案,但我想知道是否有合适的方法来做到这一点。
I'm given a string hex_txt containing a 4 digit hex number in the way outlined in the code, split up in two array entries. I need to convert it to decimal. The following is the way I'm doing it.
unsigned char hex_txt[] = "\xAB\xCD";
unsigned char hex_num[5];
unsigned int dec_num;
sprintf(hex_num, "%.2x%.2x", (int)hex_txt[0], (int)hex_txt[1]);
printf("%s\n", hex_num);
sscanf(hex_num, "%x", &dec_num);
printf("%d\n", dec_num);
Is there a faster, or more efficient way of doing this? This is my current ad hoc solution, but I'd like to know if there's a proper way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
字符串
hex_txt
包含两个字节;我猜测顺序是大端(如果是小端则反转下标)。hex_txt[0]
的字符代码为 0xAB,hex_txt[1]
的字符代码为 0xCD。使用无符号字符转换可确保您不会被有符号字符弄乱。或者,一次性完成所有操作:
The string
hex_txt
contains two bytes; I'm guessing that the order is big-endian (reverse the subscripts if it is little-endian). The character code forhex_txt[0]
is 0xAB, forhex_txt[1]
is 0xCD. The use of unsigned char casts ensures that you don't get messed up by signed characters.Or, to do it all at once:
只需使用
stdlib.h
中的strtoul()
函数即可。请参见以下示例:
Simply use
strtoul()
function fromstdlib.h
.See the following example:
我可能会胡言乱语,但如果你使用:
那么实际上你只定义了 2 个字节:
因此要将其转换为 int 你可以这样做:
I might be babbling but if you use:
then in effect you just define 2 bytes:
so to convert this to an int you can do this:
这就是我所做的:
并且(你会讨厌这个,但它适用于 ASCII)我作弊:
添加:抱歉,我刚刚重新阅读了你的问题。为什么不这样做:
Here's what I do:
And (you'll hate this but it works for ASCII) I cheat:
ADDED: Sorry, I just re-read your question. Why not do:
您可能不需要它,尽管我在 此处 发布了一段 C++ 代码。
You might not need it, though there's a piece of C++ code I published here.