英文:
How to swap specific bits between two bytes based on bit map?
问题
<pre>
例如:
如果 A -> 00001010(10),B -> 01000001(65),C -> 00011010(26)(位图)
因此在交换特定位后,新的 A(A') -> 00000000,
新的 B(B') -> 01001011
解释:
A -> 00001010
C -> 00011010(交换 A 和 B 的特定位,如果 C 的特定位为1,
即第4位、第5位、第7位(从左到右的顺序)
B -> 01000001
----------------
A' -> 00000000
B' -> 01001011
</pre>
英文:
<pre>
For example:
If A -> 00001010(10), B-> 01000001(65), C -> 00011010(26)(Bit Map)
So after swapping specific bits, New A(A') -> 00000000 and
New B(B') -> 01001011
Explanation:
A -> 00001010
C -> 00011010(Swap bits b/w A and B if C's specific bit is 1,
I.e bit 4, 5, 7(direction from left to right)
B -> 01000001
----------------
A' -> 00000000
B' -> 01001011
</pre>
答案1
得分: 1
这很简单。将A
从B
中仅设置MASK
位:
- 清除
A
中所有的MASK
位:D = A & ~MASK
- 从
B
中获取仅MASK
位:E = B & MASK
- 将所需位设置到
A
:RES = D | E
在大多数编程语言中,可能如下所示:
final int a = 0b00001010;
final int b = 0b01000001;
final int c = 0b00011010;
int aa = (a & ~c) | (b & c);
int bb = (b & ~c) | (a & c);
System.out.format("a: %08d\n", new BigInteger(Integer.toBinaryString(aa)));
System.out.format("a: %08d\n", new BigInteger(Integer.toBinaryString(bb)));
附言: 这只是基本的位操作。
英文:
This is pretty simple. To set A
from B
only bits MASK
:
- Clear all bits
MASK
fromA
:D = A & ~MASK
- Get only bits
MASK
fromB
:E = B & MASK
- Set required bits to
A
:RES = D | E
In most of languages it could look like this:
final int a = 0b00001010;
final int b = 0b01000001;
final int c = 0b00011010;
int aa = (a & ~c) | (b & c);
int bb = (b & ~c) | (a & c);
System.out.format("a: %08d\n", new BigInteger(Integer.toBinaryString(aa)));
System.out.format("a: %08d\n", new BigInteger(Integer.toBinaryString(bb)));
P.S. This is only basic bit operations.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论