下面的代码也应该回答这个问题。
#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:我两年前作出评论。 –