我對按位操作有一些熟悉,但是這個功能剛好超過了我的腦海。C中的按位邏輯
void binary_print(unsigned int value) {
unsigned int mask = 0xff000000; // Start with a mask for the highest byte.
unsigned int shift = 256*256*256; // Start with a shift for the highest byte.
unsigned int byte, byte_iterator, bit_iterator;
for (byte_iterator=0; byte_iterator < 4; byte_iterator++) {
byte = (value & mask)/shift; // Isolate each byte.
printf(" ");
for (bit_iterator=0; bit_iterator < 8; bit_iterator++) {
// Print the byte's bits.
if (byte & 0x80) // If the highest bit in the byte isn't 0,
printf("1"); // print a 1.
else
printf("0"); // Otherwise, print a 0.
byte *= 2; // Move all the bits to the left by 1.
}
mask /= 256; // Move the bits in mask right by 8.
shift /= 256; // Move the bits in shift right by 8.
}
}
此函數接收位標誌爲open()
功能,並與添加適當的標籤,一個display_flags功能的幫助下產生下面的輸出:
O_RDONLY : 0 : 00000000 00000000 00000000 00000000
O_WRONLY : 1 : 00000000 00000000 00000000 00000001
O_RDWR : 2 : 00000000 00000000 00000000 00000010
O_APPEND : 1024 : 00000000 00000000 00000100 00000000
O_TRUNC : 512 : 00000000 00000000 00000010 00000000
O_CREAT : 64 : 00000000 00000000 00000000 01000000
O_WRONLY|O_APPEND|O_CREAT : 1089 : 00000000 00000000 00000100 01000001
我沒有問題,理解輸出,但我不明白實際的過程:
byte = (value & mask)/shift
如何隔離個別位?- 爲什麼
if(byte & 0x80)
的意思是「如果字節中的最高位不是0?」 - 這些行如何做:
byte *= 2;
,mask /= 256;
和shift /= 256;
移動位,爲什麼這個操作有意義?
非常感謝您對此類詳細的解釋(輕描淡寫)! – Leon 2013-02-16 15:53:10