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 out but I’m getting "0xffffff9b" or something of the sort. Is there a way to get the notation without the “f’s”?
I would like to print out each element looking something like:
0x9a, 0x43, 0x0D, etc.
This:
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 intis undefined. If you really wanted to print the address, the right way to do it would be:(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 tellsprintfto 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:
you can print element 5 like this:
or, if you want a leading zero:
The
"%x"format requires anunsigned intargument, and theunsigned charvalue you’re passing is implicitly promoted tounsigned int, so this is type-correct. You can use"%x"to print the hex digitsathroughfin 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.