下面的代碼也應該回答這個問題。
#include <stdio.h>
int getByte(int x, int n);
void main()
{
int x = 0xAABBCCDD;
int n;
for (n=0; n<=3; n++) {
printf("byte %d of 0x%X is 0x%X\n",n,x,getByte(x,n));
}
}
// extract byte n from word x
// bytes numbered from 0 (LSByte) to 3 (MSByte)
int getByte(int x, int n)
{
return (x >> (n << 3)) & 0xFF;
}
輸出是
byte 0 of 0xAABBCCDD is 0xDD
byte 1 of 0xAABBCCDD is 0xCC
byte 2 of 0xAABBCCDD is 0xBB
byte 3 of 0xAABBCCDD is 0xAA
概念可以基於templatetypedef的解釋說明和擴大如下。
(3) (2) (1) (0)
aaaaaaaa bbbbbbbb cccccccc dddddddd
{(3),(2),(1),(0)} --> {(3)}
???????? ???????? ???????? aaaaaaaa // x>>(3*8) where 3 == n
& 00000000 00000000 00000000 11111111 // 0xFF
-----------------------------------
00000000 00000000 00000000 aaaaaaaa // (x >> (8 * n)) & 0xFF
{(3),(2),(1),(0)} --> {(2)}
???????? ???????? aaaaaaaa bbbbbbbb // x>>(2*8) where 2 == n
& 00000000 00000000 00000000 11111111 // 0xFF
-----------------------------------
00000000 00000000 00000000 bbbbbbbb
{(3),(2),(1),(0)} --> {(1)}
???????? aaaaaaaa bbbbbbbb cccccccc // x>>(1*8) where 1 == n
& 00000000 00000000 00000000 11111111 // 0xFF
-----------------------------------
00000000 00000000 00000000 cccccccc
{(3),(2),(1),(0)} --> {(0)}
aaaaaaaa bbbbbbbb cccccccc dddddddd // x>>(0*8) where 0 == n
& 00000000 00000000 00000000 11111111 // 0xFF
-----------------------------------
00000000 00000000 00000000 dddddddd
Note (x >> (8 * n)) & 0xFF is equivalent to (x >> (n << 3)) & 0xFF.
64 32 16 8 4 2 1
----------------
0 0 0 0 0 1 1 // (n==3)
0 0 1 1 0 0 0 // (n*8==n<<3==24)
----------------
0 0 0 0 0 1 0 // (n==2)
0 0 1 0 0 0 0 // (n*8==n<<3==16)
----------------
0 0 0 0 0 0 1 // (n==1)
0 0 0 1 0 0 0 // (n*8==n<<3==8)
----------------
來源
2013-04-19 14:24:34
oon
標籤功課(不得不放棄「邏輯」,因爲最多5個標籤。) –
@JBentley:我兩年前作出評論。 –