根据位图在两个字节之间如何交换特定位?

huangapple go评论104阅读模式
英文:

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 -&gt;  00001010
  C -&gt;  00011010(Swap bits b/w A and B if C&#39;s specific bit is 1,
                 I.e bit 4, 5, 7(direction from left to right)
  B -&gt;  01000001
----------------
  A&#39; -&gt; 00000000
  B&#39; -&gt; 01001011

</pre>

答案1

得分: 1

这很简单。将AB中仅设置MASK位:

  1. 清除A中所有的MASK位:D = A & ~MASK
  2. B中获取仅MASK位:E = B & MASK
  3. 将所需位设置到ARES = 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:

  1. Clear all bits MASK from A: D = A &amp; ~MASK
  2. Get only bits MASK from B: E = B &amp; MASK
  3. 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 &amp; ~c) | (b &amp; c);
int bb = (b &amp; ~c) | (a &amp; c);

System.out.format(&quot;a: %08d\n&quot;, new BigInteger(Integer.toBinaryString(aa)));
System.out.format(&quot;a: %08d\n&quot;, new BigInteger(Integer.toBinaryString(bb)));

P.S. This is only basic bit operations.

huangapple
  • 本文由 发表于 2020年9月11日 14:43:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63842017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定