如何在 printf 的一行中列印出存盤整數中的第二個位元組,如第二個 printf() 所示
unsigned int aNum = 258; // 4 bytes in allocated memory
unsigned char * newP = &aNum;
printf("\n with a pre-created pointer i",newP[1]); //getting the second byte[02]
printf("\n address without a pre-created pointer i",(unsigned char)aNum); // getting the first byte[01]
uj5u.com熱心網友回復:
考慮這個解決方案:
#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 x", i, (unsigned int) ((unsigned char *) &aNum)[i]);
}
}
uj5u.com熱心網友回復:
我認為使用按位運算子會更好:
unsigned num = ...
unsigned char lowest_byte = num & 0xFF;
unsigned char second_low_byte = ((num & 0xFF00) >> 8);
printf ("\nfirst byte: i, second byte: i\n", (unsigned) lowest_byte, (unsigned)second_low_byte);
當然,您實際上并不需要臨時變數,您可以直接在運算元中進行按位printf運算。
如果您絕對需要使用陣列,那么就是這樣:
unsigned char *ptr = (unsigned char*)#
printf ("\nfirst byte: x, second byte: x\n", ptr[0], ptr[1]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412254.html
標籤:
下一篇:將簡單值存盤在C中的矩陣中
