Converting hex to string in C?

戏子无情 提交于 2019-11-29 07:14:12

0xaa overflows when plain char is signed, use 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!