Search code examples
cc89ansi-c

How do print exactly X digits in hex


I have an integer, want to print exactly 6 digits of hex.

I tried

fprintf(stdout,"%06x\n",number);

it does work perfectly when the MSBs are 0, but I use 2's completment for negative numbers, and it doesn't work for them

for example. here is what it prints

ffffff9f negative number, 8 digits.

0b680c - positive number, OK, 6 digits.

my numbers would never be too large to fit in 24bits, so they should always fit in 6 hexadecimal characters, but how do I make it, so it will trim the left part to always print exactly 6 digits?


Solution

  • Convert the number to unsigned long, as a side-effect this will ensure 2's complement representation even if the target used some other representation for signed negative numbers; then mask with 0xFFFFFF. I.e.

    fprintf(stdout,"%06lx\n", (unsigned long)number & 0xFFFFFFUL);
    

    which is guaranteed to be maximally portable; i.e. work on targets that has 16-bit ints, different representations for negative numbers etc. (I believe the outer cast to unsigned long is not necessary because 0xFFFFFF should be