gpt4 book ai didi

java - 如何在一个字节中展开位?

转载 作者:行者123 更新时间:2023-12-01 10:07:07 24 4
gpt4 key购买 nike

在 Java 中,我有 2 个字节:

byte b1 = (byte) 0b11111111, b2 = (byte) 0b00000000;

我想混合它们,以便每个第一位都来自 b1,而另一个来自 b2(从左到右阅读)。输入的前半部分和后半部分是分开完成的,因此结果是 2 个字节。结果 b3b4 如下所示。

byte b3 = (byte) 0b10101010, b4 = 0b10101010;

为了说明这些位如何是唯一的(使用字母来指定唯一位):

byte b1 = (byte) 0bHGFEDCBA, b2 = (byte) 0bPONMLKJI;

结果将是:

byte b3 = (byte) 0bHPGOFNEM, b4 = 0bDLCKBJAI;

或者,以图形方式,

    +---+---+---+---+---+---+---+---+
b1 | H | G | F | E | D | C | B | A |
+---+---+---+---+---+---+---+---+
| | | | | | | |
| | | | | | | +--------------------------------------------+
| | | | | | +----------------------------------------+ |
| | | | | +------------------------------------+ | |
| | | | +--------------------------------+ | | |
| | | +-------------------+ | | | |
| | +---------------+ | | | | |
| +-----------+ | | | | | |
+-------+ | | | | | | |
| | | | | | | |
+---+---+---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+
b3 | H | P | G | O | F | N | E | M | b4 | D | L | C | K | B | J | A | I |
+---+---+---+---+---+---+---+---+ +---+---+---+---+---+---+---+---+
| | | | | | | |
+-----------+ | | | | | | |
| +---------------+ | | | | | |
| | +-------------------+ | | | | |
| | | +-----------------------+ | | | |
| | | | +------------------------------------+ | | |
| | | | | +----------------------------------------+ | |
| | | | | | +--------------------------------------------+ |
| | | | | | | +------------------------------------------------+
| | | | | | | |
+---+---+---+---+---+---+---+---+
b2 | P | O | N | M | L | K | J | I |
+---+---+---+---+---+---+---+---+

实现这一目标的最简单方法是什么?

最佳答案

如果,正如您所说,您一心只想着一句俏话,那么:

public static int interleave(short b1, short b2) {
return((int)(((b2 * 0x0101010101010101L & 0x8040201008040201L) *
0x0102040810204081L >> 49) & 0x5555) |
(int)(((b1 * 0x0101010101010101L & 0x8040201008040201L) *
0x0102040810204081L >> 48) & 0xAAAA));
}

这将返回一个 int,其中 b3 和 b4 作为低 16 位,您可以将其移位并屏蔽掉:

int b3b4 = interleave(b1, b2);
int b3 = b3b4 >> 8;
int b4 = b3b4 & 0b11111111;

算法由Interleave bits with 64-bit multiply提供

关于java - 如何在一个字节中展开位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36369006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com