Printing the hexadecimal representation of a char array[]

后端 未结 3 1461
盖世英雄少女心
盖世英雄少女心 2020-12-30 08:22

I\'ve got an array of 8 bytes that I\'m trying to print out the hexadecimal notation for. Using printf(\"%x\", array) I can get at the first byte and print it

3条回答
  •  执念已碎
    2020-12-30 08:39

    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.

提交回复
热议问题