Convert hex to string in C?

Hi, I am using digi dynamic c. I am trying to convert this to a string

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

Currently, when I do printf instructions, it should be as follows:

 printf("This is element 0: %x\n", readingreg[0]); 

But I want this on a line, so I can use a printf statement like this

  printf("This is element 0: %s\n", readingreg[0]); 

I need to send the readreg array through the TCP / IP port, for which I need to have it as a string. I can't seem to convert it to a string. Thank you for your help. Also, if someone can tell me how to do each element at a time, and not the whole array, that would be nice, since there will only be 4 elements.

+6
source share
2 answers

0xaa overflows when signing a simple char , 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; } 
+6
source

If your computer is large, you can do the following:

 char str[9]; sprintf(str, "%x", *(uint32_t *)readingreg); 

If your machine is a little oriented, you will have to change 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 statement.

I get the following output:

 printf("0x%s\n", str); 

0x4aaaaaa0

+2
source

Source: https://habr.com/ru/post/974710/


All Articles