Printing string in hex?

26,047

Solution 1

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

You can't use sizeof like that, you probably mean strlen().

And you need to cast the character to an unsigned type to be safe.

So, something like this, perhaps:

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

Note that I don't call strlen(), since there's no point in iterating over the string twice when once will do. :)

Solution 2

I think technically "string" is misleading here; you seem to be printing an array (not necessarily null-terminated) of uint8_t values.

You will need a loop in any case. If you can use C99, you could write

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

If the array is null-terminated, and you don't need the original value of string (this is often a case when passing the pointer by value), you could have

static void printArray(const uint8_t *string)
{
  while (*string) printf("%02x", *string++);
}
Share:
26,047
reox
Author by

reox

Just another PhD Student

Updated on August 02, 2022

Comments

  • reox
    reox almost 2 years

    Is this short way for printing the string in hex is correct? If not, how it should be fixed?

    uint8_t *m = string;
    int c = sizeof(string);
    while(c--){
        printf("%02x ", *(m++));
    }
    
  • Frerich Raabe
    Frerich Raabe over 11 years
    sizeof may be fine if he's dealing with a plain array, e.g. uint8_t string[] = { 0x01, 0x02, 0x03 };. However, his could would have an off-by-one (the while loops reads one character too much.
  • reox
    reox over 11 years
    @FrerichRaabe yes i'am having a uint8_t[] here... better use while(--c) in my case? but then the \00 isnt printed...
  • Frerich Raabe
    Frerich Raabe over 11 years
    @reox: Sorry, I miscounted. I had an off-by-one in my thinking, so to say ;-) I think while(c--) would be fine. However, if the array is always null-terminated you may just as well not use the c variable at all but rather just use while(*m).
  • RoundSparrow hilltx
    RoundSparrow hilltx over 7 years
    Can someone turn this into a function that returns a const char instead of printf?