1

问题及解决方案:

/** 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
  1. int 较低 = X & 0x0000ffff = X & 0b00000000000000001111111111111111 = 0b0000000000000000x 15 ... x 0

  2. int 上 = X & 0xffff0000 = X & 0b11111111111111110000000000000000 = 0bx 31 ... x 16 0000000000000000

  3. 较低 << 8 = 0b0000000000000000x 15 ... x 0 << 8 = 0b00000000x 15 ... x 0 00000000

  4. 下 >> 8 = 0b0000000000000000x 15 ... x 0 >> 8 = 0bssssssss00000000x 15 ... x 8

    • (假设X是有符号数,s则为符号位;如果为正则为 0 X,如果为负则为 1 X
  5. (下 << 8) | (下 >> 8) = 0b00000000x 15 ... x 0 00000000 | 0bsssssss00000000x 15 ... x 8 = 0bsssssssx 15 ... x 0 x 15 ... x 8

  6. 0xffff & ((lower << 8) | (lower >> 8)) = 0b000000000000000001111111111111111 & 0bssssssssx 15 ... x 0 x 15 ... x 8 = 0b00000000000000000x 7 ... x 0 x 15 ... x 8

  7. 鞋面 | (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

4

2 回答 2

2

是的,这比必要的更难理解。

我认为这更容易理解:

int lowest2     = (X & 0x000000FF) << 8; // lowest byte moved 8 bits left
int nextLowest2 = (X & 0x0000FF00) >> 8; // next lowest byte move 8 bits right
int upper4      = (X & 0xFFFF0000);
return upper4 | lowest2 | nextLowest2;

那么当 X = 0x12345678 时:

upper4 | lowest2 | nextLowest2 = 0x12340000 | 0x00007800 | 0x00000056;

但当然,如果你分析你给你的解决方案,你会得到同样的结果:

如果上和下定义为:

int lower = X & 0x0000FFFF
int upper = X & 0xffff0000;

然后:

X                                                = 0x12345678
lower                                            = 0x00005678
(lower << 8)                                     = 0x00567800
(lower >> 8)                                     = 0x00000056
((lower << 8) | (lower >> 8))                    = 0x00567856
(0xFFFF & ((lower << 8) | (lower >> 8)))         = 0x00007856
upper                                            = 0x12340000
upper | (0xffff & ((lower << 8) | (lower >> 8))) = 0x12345678
于 2013-08-10T02:21:05.313 回答
0

给定的解决方案是正确的,但过于复杂,因此比必要的更难理解。以下解决方案更容易理解:

return X & 0xffff0000 | ((X & 0xff00) >> 8) | ((X & 0xff) << 8);

它只是从数字中提取三个部分并重新排列它们。要理解它,请考虑每个|- 分隔的组件,考虑它选择的数字的哪一部分以及该部分在结果中的最终位置。

于 2013-08-10T01:36:33.640 回答