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

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

How to swap specific bits between two bytes based on bit map?

问题

  1. <pre>
  2. 例如:
  3. 如果 A -> 00001010(10),B -> 01000001(65),C -> 00011010(26)(位图)
  4. 因此在交换特定位后,新的 A(A') -> 00000000
  5. 新的 B(B') -> 01001011
  6. 解释:
  7. A -> 00001010
  8. C -> 00011010(交换 A B 的特定位,如果 C 的特定位为1
  9. 即第4位、第5位、第7位(从左到右的顺序)
  10. B -> 01000001
  11. ----------------
  12. A' -> 00000000
  13. B' -> 01001011
  14. </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

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

在大多数编程语言中,可能如下所示:

  1. final int a = 0b00001010;
  2. final int b = 0b01000001;
  3. final int c = 0b00011010;
  4. int aa = (a & ~c) | (b & c);
  5. int bb = (b & ~c) | (a & c);
  6. System.out.format("a: %08d\n", new BigInteger(Integer.toBinaryString(aa)));
  7. 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:

  1. final int a = 0b00001010;
  2. final int b = 0b01000001;
  3. final int c = 0b00011010;
  4. int aa = (a &amp; ~c) | (b &amp; c);
  5. int bb = (b &amp; ~c) | (a &amp; c);
  6. System.out.format(&quot;a: %08d\n&quot;, new BigInteger(Integer.toBinaryString(aa)));
  7. 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:

确定