如何在一个字节中转换bool数组,然后再转换回bool数组 [英] how to convert bool array in one byte and later convert back in bool array

查看:182
本文介绍了如何在一个字节中转换bool数组,然后再转换回bool数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

 公共静态字节[] BitArrayToByteArray(BitArray bits)
{
byte [] ret = new byte [Math.Max(1,bits.Length / 8)] ;
bits.CopyTo(ret,0);
回程;
}

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

解决方案

这就是我要实现的方式。 / p>

要将 bool [] 转换为 byte

 私有静态字节ConvertBoolArrayToByte(bool []源)
{
字节结果= 0;
//假设数组中的元素数量不能超过8个!
int索引= 8-source.Length;

//遍历数组
foreach(源中的布尔b)
{
//如果元素为true,则在该位置设置位
如果(b)
结果| =(字节)(1<<(7-索引));

index ++;
}

返回结果;
}

要将字节转换为长度为8的布尔数组:

 私有静态布尔值[] ConvertByteToBoolArray(字节b)
{
//准备返回结果
bool []结果=新的bool [8];

//检查字节中的每个位。如果1设置为true,如果0设置为false
,则(int i = 0; i< 8; i ++)
result [i] =(b&(1<< i) )== 0?假:真;

//反转数组
Array.Reverse(result);

返回结果;
}


I would like to pack bool array with max length 8 in one byte, send it over network and then unpack it back to bool array. Tried some solutions here already but it didn't work. I'm using Mono.

I made BitArray and then tried to convert it in byte

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

but I'm getting errors telling only int and long type can be used. Tried int instead of byte but same problem. I would like to avoid BitArray and use simple conversion from bool array to byte if possible

解决方案

Here's how I would implement this.

To convert the bool[] to a 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;
}

To convert a byte to an array of bools with length 8:

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 ? false : true;

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

    return result;
}

这篇关于如何在一个字节中转换bool数组,然后再转换回bool数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆