在C#中交换正32位整数的位

Ler*_*ica 2 c# bit-manipulation

所以我试图解决这个问题:

您将获得随机32位正整数,您需要做的是将第3,第4和第5位的位值与第24位,第25位和第26位的值进行交换.

das*_*ght 6

假设这是一个你不想要一个显式解决方案的问题,这里有一个提示:使用的方法屏蔽所讨论的位&,执行移位,OR然后使用按位|.

您可以使用0x00000034掩码"删除"第3,4和5位,使用掩码"删除"第24,25和26位0x07000000.

看看这个解决方案的位置反转问题的灵感.

编辑:(回应"不是作业"评论)由于这不是一个功课,这里有一个更深入的解释:

unsigned int val = ... // your value
unsigned int bits_03_04_05 = val & 0x00000034;
unsigned int bits_24_25_26 = val & 0x07000000;
// Cut out "holes" at bits 3, 4, 5, 24, 25, and 26 of the original value
unsigned int res = val & ~(0x00000034 | 0x07000000);
// Put bits 3, 4, and 5 in place
res |= bits_03_04_05 << 21;
// Put bits 23, 24, and 25 in place
res |= bits_24_25_26 >> 21;
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 5

怎么样:

    // snag the values from 3,4,5 (small) and 24,25,26 (large)
    int small = value & (7 << 2), large = value & (7 << 23);

    // remove the old values, and add in the new ones
    value = (value ^ (small | large)) | (large >> 21) | (small << 21);
Run Code Online (Sandbox Code Playgroud)

(将第1位计为LSB;如果你的意思是第0位是LSB,则将数字调整为1)