gpt4 book ai didi

c# - 如何在一个字节中转换 bool 数组,然后再转换回 bool 数组

转载 作者:行者123 更新时间:2023-11-30 13:26:25 33 4
gpt4 key购买 nike

我想将最大长度为 8 的 bool 数组打包成一个字节,通过网络发送它,然后将其解压回 bool 数组。已经在这里尝试了一些解决方案,但没有用。我正在使用单声道。

我制作了 BitArray,然后尝试将其转换为字节

public static byte[] BitArrayToByteArray(BitArray bits)
{
byte[] ret = new byte[Math.Max(1, bits.Length / 8)];
bits.CopyTo(ret, 0);
return ret;
}

但我收到错误提示只能使用 int 和 long 类型。尝试使用 int 而不是 byte 但同样的问题。我想避免使用 BitArray,并尽可能使用从 bool 数组到字节的简单转换

最佳答案

下面是我将如何实现它。

bool[] 转换为 byte:

private static byte ConvertBoolArrayToByte(bool[] source)
{
byte result = 0;
// This assumes the array never contains more than 8 elements!
int index = 8 - source.Length;

// Loop through the array
foreach (bool b in source)
{
// if the element is 'true' set the bit at that position
if (b)
result |= (byte)(1 << (7 - index));

index++;
}

return result;
}

将字节转换为长度为 8 的 bool 数组:

private static bool[] ConvertByteToBoolArray(byte b)
{
// prepare the return result
bool[] result = new bool[8];

// check each bit in the byte. if 1 set to true, if 0 set to false
for (int i = 0; i < 8; i++)
result[i] = (b & (1 << i)) != 0;

// reverse the array
Array.Reverse(result);

return result;
}

关于c# - 如何在一个字节中转换 bool 数组,然后再转换回 bool 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24322417/

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