在一行中打印出 printf() 中的第二个字节

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

如何在 printf 的一行中打印出存储整数中的第二个字节,如下所示 在第二个 printf()

unsigned int aNum = 258; // 4 bytes in allocated memory
unsigned char * newP = &aNum;

printf("\n with a pre-created pointer %02i",newP[1]); //getting the second byte[02]
printf("\n address without a pre-created pointer %02i",(unsigned char)aNum); // getting the first byte[01]
 

我觉得用按位运算符会更好:

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);

你当然不需要临时变量,你可以直接在printf操作数中进行按位运算。


如果你绝对需要使用数组,那么就是这样:

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

考虑这个解决方案:

#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]);
    }
}