如果在开始时(8 位)你有:abcdefgh,并且你想交换第 5 位和第 3 位位置的值,那么输出如下所示:abedcfgh。
可能有十几种方法可以做到这一点。
(我已经使用位位置 5 和位位置 3 使用正常位位置编号编写了这个,其中低位(最低位/最低有效位/LSB)被视为位位置编号 0 - 如果你真的想要交换第 5 位和第 3 位,这将是第 4 位和第 2 位。如果您想要从左侧/MSB 开始的第 5 位和第 3 位,那也将有所不同。)
到目前为止,您有 $t1 = abcdefgh000 和 $t2= abcdefgh00000。这可能不会太有用。
但是,如果您改为向右移动,您将拥有000abcde 和00000abc,这越来越接近于隔离两个感兴趣的位。使用常数为 1 的 & 运算符,您将得到 0000000e 和 0000000c,这是两个 1 位字段的基本提取。
不过,您实际上并不需要像我们通常在位字段提取中那样对这些位进行右对齐,因为它们可以使用右移和左移直接移动到新的所需位位置。
您想要的一个中间值是原件的副本,在感兴趣的位置有孔(零),而其他是在位 3 位置的 c 的值,否则被零包围,值 e 在第 5 位的位置类似地被零包围。
76543210
abcdefgh original value
11010111 mask, constant value 215 decimal
======== & bitwise "and" operation
ab0d0fgh intermediate value #1
76543210
abcdefgh original value
2 shift count=2, decimal
======== >> binary right shift operation
00abcdef intermediate value #2
76543210
00abcdef intermediate value #2
00001000 mask, 8 (decimal)
======== & bitwise and operation
0000c000 intermediate value #3, "c" in the bit 3 position
76543210
ab0d0fgh intermediate value #1
0000c000 intermediate value #3
======== | bitwise or operation
ab0dcfgh intermediate value #4
76543210
abcdefgh original value
2 shift count=2, decimal
======== << binary left shift operation
cdefgh00 intermediate value #5
76543210
cdefgh00 intermediate value #5
00100000 mask, 32 (decimal)
======== & bitwise and operation
00e00000 intermediate value #6, "e" in the bit 5 position
76543210
ab0dcfgh intermediate value #4
00e00000 intermediate value #6
======== | bitwise or operation
abedcfgh desired output
对于| 的(按位或)运算,加法也可以在这里工作,因为我们知道一个操作数有 0,而另一个有 0 或 1,因此不会发生进位,所以 + 的结果(加法)将与 | 相同(按位或运算)。
我已经用 8 位显示了这个,你必须调整为完整的 32 位。