Printing the hexadecimal representation of a char array[]

Print a string in hex:

void print_hex(const char *string)
{
        unsigned char *p = (unsigned char *) string;

        for (int i=0; i < strlen(string); ++i) {
                if (! (i % 16) && i)
                        printf("\n");

                printf("0x%02x ", p[i]);
        }
        printf("\n\n");
}

char *umlauts = "1 ä ö ü  Ä Ö Ü  é É  ß € 2";

print_hex(umlauts);

0x31 0x20 0xc3 0xa4 0x20 0xc3 0xb6 0x20 0xc3 0xbc 0x20 0x20 0xc3 0x84
0x20 0xc3 0x96 0x20 0xc3 0x9c 0x20 0x20 0xc3 0xa9 0x20 0xc3 0x89 0x20
0x20 0xc3 0x9f 0x20 0xe2 0x82 0xac 0x20 0x32

This is what I did, its a little bit easier with a function and I use for debugging and logging memory.

void print_hex_memory(void *mem) {
  int i;
  unsigned char *p = (unsigned char *)mem;
  for (i=0;i<128;i++) {
    printf("0x%02x ", p[i]);
    if ((i%16==0) && i)
      printf("\n");
  }
  printf("\n");
}

This:

printf("%x", array);

will most likely print the address of the first element of your array in hexadecimal. I say "most likely" because the behavior of attempting to print an address as if it were an unsigned int is undefined. If you really wanted to print the address, the right way to do it would be:

printf("%p", (void*)array);

(An array expression, in most contexts, is implicitly converted to ("decays" to) a pointer to the array's first element.)

If you want to print each element of your array, you'll have to do so explicitly. The "%s" format takes a pointer to the first character of a string and tells printf to iterate over the string, printing each character. There is no format that does that kind of thing in hexadecimal, so you'll have to do it yourself.

For example, given:

unsigned char arr[8];

you can print element 5 like this:

printf("0x%x", arr[5]);

or, if you want a leading zero:

printf("0x%02x", arr[5]);

The "%x" format requires an unsigned int argument, and the unsigned char value you're passing is implicitly promoted to unsigned int, so this is type-correct. You can use "%x" to print the hex digits a throughf in lower case, "%X" for upper case (you used both in your example).

(Note that the "0x%02x" format works best if bytes are 8 bits; that's not guaranteed, but it's almost certainly the case on any system you're likely to use.)

I'll leave it to you to write the appropriate loop and decide how to delimit the output.

Tags:

C

Hex