13

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++));
}
Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
reox
  • 5,036
  • 11
  • 53
  • 98

2 Answers2

23

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. :)

unwind
  • 391,730
  • 64
  • 469
  • 606
  • `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. – Frerich Raabe Oct 04 '12 at 10:24
  • @FrerichRaabe yes i'am having a uint8_t[] here... better use `while(--c)` in my case? but then the \00 isnt printed... – reox Oct 04 '12 at 10:26
  • @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)`. – Frerich Raabe Oct 04 '12 at 10:40
  • 1
    Can someone turn this into a function that returns a const char instead of printf? – RoundSparrow hilltx Jan 13 '17 at 16:56
3

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++);
}
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207