Print a string in hexadecimal format?

Is this short way to print a string in hexadecimal format correct? If not, how should this be fixed?

uint8_t *m = string; int c = sizeof(string); while(c--){ printf("%02x ", *(m++)); } 
+7
source share
2 answers

No "oneliner", no. Also, your code looks broken.

You cannot use sizeof like this, you probably mean strlen() .

And you need to drop the character to an unsigned type so that it is safe.

So, something like this is possible:

 void print_hex(const char *s) { while(*s) printf("%02x", (unsigned int) *s++); printf("\n"); } 

Please note that I do not call strlen() , as it makes no sense to iterate over the line twice when this is done. :)

+17
source

I think that technically the β€œstring” is misleading; you seem to be printing an array (not necessarily terminating zero) of uint8_t values.

In any case, you will need a loop. If you can use C99, you can write

 for (size_t i = 0; i < sizeof(string); ++i) printf("%02x", string[i]); 

If the array has zero completion and you don't need the original string value (this often happens when passing a pointer by value), you could have

 static void printArray(const uint8_t *string) { while (*string) printf("%02x", *string++); } 
+2
source

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


All Articles