C语言 在C中将十六进制转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25630947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting hex to string in C?
提问by Dale Reed
Hello I am using digi dynamic c. I am trying to convert this in to string
您好,我正在使用 digi dynamic c。我正在尝试将其转换为字符串
char readingreg[4];
readingreg[0] = 4a;
readingreg[1] = aa;
readingreg[2] = aa;
readingreg[3] = a0;
Currently when I do printfstatements it has to be like this:
目前,当我做printf陈述时,它必须是这样的:
printf("This is element 0: %x\n", readingreg[0]);
But I want this in string so I can use printfstatement like this
但我想要这个字符串,所以我可以使用这样的printf语句
printf("This is element 0: %s\n", readingreg[0]);
I am essentialy sending the readingreg array over TCP/IP Port, for which I need to have it as string. I cant seem to be able to convert it into string. Thanks for your help. Also if someone can tell me how to do each element at a time rather than whole array, that would be fine to since there will only be 4 elements.
我本质上是通过 TCP/IP 端口发送 readingreg 数组,为此我需要将它作为字符串。我似乎无法将其转换为字符串。谢谢你的帮助。此外,如果有人能告诉我如何一次处理每个元素而不是整个数组,那也没关系,因为只有 4 个元素。
回答by David Ranieri
0xaaoverflows when plain charis signed, use unsigned char:
0xaa当普通char签名时溢出,请使用unsigned char:
#include <stdio.h>
int main(void)
{
unsigned char readingreg[4];
readingreg[0] = 0x4a;
readingreg[1] = 0xaa;
readingreg[2] = 0xaa;
readingreg[3] = 0xa0;
char temp[4];
sprintf(temp, "%x", readingreg[0]);
printf("This is element 0: %s\n", temp);
return 0;
}
回答by Fiddling Bits
If your machine is big endian, you can do the following:
如果您的机器是大端,您可以执行以下操作:
char str[9];
sprintf(str, "%x", *(uint32_t *)readingreg);
If your machine is little endian you'll have to swap the byte order:
如果您的机器是小端,则必须交换字节顺序:
char str[9];
uint32_t host;
host = htonl(*(uint32_t *)readingreg);
sprintf(str, "%x", host);
If portability is a concern, you should use method two regardless of your endianness.
如果考虑可移植性,则无论字节顺序如何,都应使用方法二。
I get the following output:
我得到以下输出:
printf("0x%s\n", str);
0x4aaaaaa0
0x4aaaaa0

