YangDev
YangDev

Reputation: 13

C - Missing 0 in hexadecimal output

I had to test if my machine is using the little or the big endian. For this reason i wrote this code. I can see that my machine is using the little endian. But i dont know why the output from my first byte is only D. Should it not be 0D?

union int2byte
{
    unsigned char bytes[4];
    unsigned int hex;
};

int main(int argc, const char* argv[])
{
    union int2byte hexby;

    hexby.hex = 0xBAADF00D;

    printf("%u\n",hexby.hex);
    int counter;
    for(counter = 0; counter < 4; counter = counter + 1)
    {
        printf("Hex for Byte %u is %X.\n",counter+1, hexby.bytes[counter]); 
    }

}

Output:
3131961357
Hex for Byte 1 is D.
Hex for Byte 2 is F0.
Hex for Byte 3 is AD.
Hex for Byte 4 is BA.

Upvotes: 1

Views: 787

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595887

%X does not output leading zeros. Use %02X instead. The 2 tells it to output at least 2 digits, and the 0 tells it to pad the output on the left side with a '0' character if the output is less than 2 digits.

Upvotes: 5

Related Questions