简体   繁体   English

在C中将十六进制转换为字符串?

[英]Converting hex to string in C?

Hello I am using digi dynamic c. 您好我正在使用digi动态c。 I am trying to convert this in to string 我试图将其转换为字符串

char readingreg[4];
readingreg[0] = 4a;
readingreg[1] = aa;
readingreg[2] = aa;
readingreg[3] = a0;

Currently when I do printf statements 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 printf statement 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. 我本质上是通过TCP / IP端口发送readingreg数组,我需要将它作为字符串。 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. 此外,如果有人可以告诉我如何一次完成每个元素而不是整个数组,那就没关系,因为只有4个元素。

0xaa overflows when plain char is signed, use unsigned char : 0xaa普通char0xaa溢出,使用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;
}

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 0x4aaaaaa0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM