sách gpt4 ai đã đi

Cách chuyển đổi một mảng bool thành một byte và ngược lại thành một mảng bool

In lại 作者:行者123 更新时间:2023-11-30 13:26:25 35 4
mua khóa gpt4 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 数组到字节的简单转换

1 Câu trả lời

下面是我将如何实现它。

Sẽ 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++;
}

trả về kết quả;
}

将字节转换为长度为 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);

trả về kết quả;
}

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

35 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com