Print out the second byte in printf() in one single line

Solution 1:

Consider this solution:

#include <stdio.h>

int main(void) {
    unsigned int aNum = 0x1a2b3c4du; // 4 bytes in allocated memory

    for (int i = 0; i < 4; ++i) {
        printf("\nbyte %d  %02x", i, (unsigned int) ((unsigned char *) &aNum)[i]);
    }
}

Solution 2:

I think it would be better to use bitwise operators:

unsigned num = ...
unsigned char lowest_byte = num & 0xFF;
unsigned char second_low_byte = ((num & 0xFF00) >> 8);
printf ("\nfirst byte: %02i, second byte: %02i\n", (unsigned) lowest_byte, (unsigned)second_low_byte);

You don't really need temporary variables of course, you can do the bitwise operations directly in printf operands.


If you absolutely need to use an array, then this is the way:

unsigned char *ptr = (unsigned char*)&num;
printf ("\nfirst byte: %02x, second byte: %02x\n", ptr[0], ptr[1]);