Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
975 views
in Technique[技术] by (71.8m points)

arrays - Converting hex to string in C?

Hello I am using digi dynamic 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("This is element 0: %x
", readingreg[0]);

But I want this in string so I can use printf statement like this

  printf("This is element 0: %s
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", temp);
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...