Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing string in hex? [closed]

Tags:

c

string

hex

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++));
}
like image 728
reox Avatar asked Oct 04 '12 10:10

reox


1 Answers

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

like image 56
unwind Avatar answered Sep 26 '22 13:09

unwind