更改位掩码中的位位置

问题描述 投票:0回答:1

我需要改变位置 1 和位置 2 的位之间的顺序(从右到左开始计数)。我该怎么做?

输入 输出
1010 1100
1110 1110
0101 0011

我正在尝试诸如:

1010 & 0010 只得到位置 1

的位

1010 & 0100 只得到位置 2

的位

我的结果 = (1010 & 0010) << 1

然后我需要对最后 2 位数字应用 AND 运算

partial_result = my_result & 0010

然后应用一些操作来排序位置 2 但它看起来很复杂。

bit-manipulation bitmask
1个回答
0
投票

在使用 and 获取位置 1 和 2 的位后,您可以左移一个,右移另一个,然后返回。

input = 1010
bitpos1 = input & 0010
bitpos2 = input & 0100
output = input & 1001  // filter out bits 1 and 2
output = output | bitpos1 | bitpos2
© www.soinside.com 2019 - 2024. All rights reserved.