如何在字节数组中存储位序列[]? 更详细地:我有一个数组位数组到字节 - java
byte[] bytes;
如何将我的单个值(0和1)存储在所述阵列的单个字节? 我在找这样的东西:
bit[] bits = new bit[8];
bits[0] = 1;
bits[3] = 1;
bytes[3] = bits[];
我希望这是有道理的。谢谢
如何在字节数组中存储位序列[]? 更详细地:我有一个数组位数组到字节 - java
byte[] bytes;
如何将我的单个值(0和1)存储在所述阵列的单个字节? 我在找这样的东西:
bit[] bits = new bit[8];
bits[0] = 1;
bits[3] = 1;
bytes[3] = bits[];
我希望这是有道理的。谢谢
void setBit(int[] array, int index, boolean value) {
int x = index/32;
int y = index % 32;
int mask = 1 << y;
if (value) {
array[x] |= mask;
}
else {
array[x] &= (0xFFFFFFFF^mask);
}
}
boolean getBit(int[] array, int index) {
int x = index/32;
int y = index % 32;
int mask = 1 << y;
return (array[x] & mask) != 0;
}
一个布尔值可以用来表示一个位,但它占用更多的内存。你可以使用bitwise运营商,以节省内存,这里有一个例子:
int n = 0;
n |= 1 << 1; // Set bit 1 to true, n is 2
n |= 1 << 3; // Set bit 3 to true, n is 10
bool b0 = n & (1 << 3) > 0; // True
n &= 1 << 3; // Set bit 3 to false, n is 2
bool b1 = n & (1 << 1) > 0; // True
bool b2 = n & (1 << 2) > 0; // False
bool b3 = n & (1 << 3) > 0; // False
你可以用'1 << something'来代替每个'Math.pow' –
@DavidWallace好的,刚刚意识到这是行得通的。去编辑我的答案... – PlasmaPower
这对我来说更像是一个记忆问题,而不是真假,所以一个布尔函数对我来说不会有效。 – Rakim
你可以把0和1成'String'和使用'Byte.parseByte'为2的基数? –
我需要不时更改字节序列,所以它不会是一个好主意,因为我将不得不重复重建序列,而不是仅将新值添加/交换到所需的索引posission – Rakim
@DavidWallace是的,但它是内存效率低下。 – PlasmaPower