Is there a char for a hex function for C?

I have a char array with data from a text file and I need to convert it to hex format. Is there such a function for C.

Thank you in advance!

+4
source share
3 answers

If I understand the question correctly (there are no guarantees), you have a text string representing a number in decimal format ("1234"), and you want to convert it to a string in hexadecimal format ("4d2").

Assuming that's right, it would be best to convert the input string to an integer using sscanf() or strtol() , and then use sprintf() using the %x conversion specifier to write the hexadecimal version to another string

 char text[] = "1234"; char result[SIZE]; // where SIZE is big enough to hold any converted value int val; val = (int) strtol(text, NULL, 0); // error checking omitted for brevity sprintf(result, "%x", val); 
+5
source

I assume that you want to be able to display the hexadecimal values โ€‹โ€‹of the individual bytes in your array, sort of like dump command output. This is a method for mapping one byte from this array.

For zero output width, an initial zero in the format is required. You can in upper or lower case X to get a representation of upper or lower case. I recommend treating them as unsigned, so there is no confusion in the sign bits.

 unsigned char c = 0x41; printf("%02X", c); 
+4
source

You can use atoi and sprintf / snprintf . Here is a simple example.

 char* c = "23"; int number = atoi(c); snprintf( buf, sizeof(buf), "%x", number ); 
+2
source

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


All Articles