问题及解决方案:
/** Return the result of swapping the two lower-order bytes of X.
* For example, if X is 0x12345678, then swap(X) is 0x12347856. */
static int swapLower(int X) {
/* Solution */
int lower = X & 0x0000ffff;
int upper = X & 0xffff0000;
return upper | (0xffff & ((lower << 8) | (lower >> 8)));
}
我对如何理解解决方案感到困惑。我试图通过逻辑工作,但我不明白。
另外,我不知道如何首先提出解决方案!
编辑:
特性:
x & 1 = x
x & 0 = 0
x | 1 = 1
x | 0 = x
int 较低 = X & 0x0000ffff = X & 0b00000000000000001111111111111111 = 0b0000000000000000x 15 ... x 0
int 上 = X & 0xffff0000 = X & 0b11111111111111110000000000000000 = 0bx 31 ... x 16 0000000000000000
较低 << 8 = 0b0000000000000000x 15 ... x 0 << 8 = 0b00000000x 15 ... x 0 00000000
下 >> 8 = 0b0000000000000000x 15 ... x 0 >> 8 = 0bssssssss00000000x 15 ... x 8
- (假设
X
是有符号数,s
则为符号位;如果为正则为 0X
,如果为负则为 1X
)
- (假设
(下 << 8) | (下 >> 8) = 0b00000000x 15 ... x 0 00000000 | 0bsssssss00000000x 15 ... x 8 = 0bsssssssx 15 ... x 0 x 15 ... x 8
0xffff & ((lower << 8) | (lower >> 8)) = 0b000000000000000001111111111111111 & 0bssssssssx 15 ... x 0 x 15 ... x 8 = 0b00000000000000000x 7 ... x 0 x 15 ... x 8
鞋面 | (0xffff & ((lower << 8) | (lower >> 8))) = 0bx 31 ... x 16 0000000000000000 | 0b00000000000000000x 7 ... x 0 x 15 ... x 8 = x 31 ... x 16 x 7 ... x 0 x 15 ... x 8