【问题标题】:how to convert bool array in one byte and later convert back in bool array如何将布尔数组转换为一个字节,然后再转换回布尔数组
【发布时间】:2014-08-10 22:12:15
【问题描述】:

我想将最大长度为 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 数组到字节的简单转换

【问题讨论】:

  • 你能具体说明你尝试了什么吗?给我们看一些代码?您能否向我们展示输入数据和所需的输出数据?实际代码将产生重大影响,并防止投票失败。
  • 你能发布确切的错误信息吗?

标签: c# data-conversion


【解决方案1】:

无 Array.Reverse 版本:

public static void Byte2Flags(bool[] flags, byte range)
{
    if (flags == null || flags.Length < 8)
    {
        return;
    }

    for (int i = 0; i < 8; i++)
        flags[i] = (range & (1 << i)) > 0;
}

public static byte Flags2Byte(bool[] flags)
{
    byte range = 0;
    if (flags == null || flags.Length < 8)
    {
        range = 0;
    }

    for (int i = 0; i < 8; i++)
    {
        if (flags[i])
        {
            range |= (byte)(1 << i);
        }
    }

    return range;
}

以及如何测试:

    bool[] flags = new bool[8];
    byte b;

    for(int i = 0; i < 256; i++)
    {
        b = (byte)i;
        Byte2Flags(flags, b);
        byte back = Flags2Byte(flags);

        if(b != back)
        {
            //Not Match!
        }
    }

【讨论】:

    【解决方案2】:

    这里有一系列方法可以做到这一点

    using System;
    using System.Text;                  
    public class Program
    {
        public void Main(){     
          byte _num = 1;
            Console.WriteLine(ReadAllBits(WriteBools(new bool[] {true,true,false,false,false,false,false,true})));
        }
        
        public string ReadAllBits(byte _mask){
            string _data = "";
            for(int i = 0; i < 8; i++){
                if((_mask& (1<<i)) !=0){
                    _data += "1";
                }else{
                    _data+="0";
                }
            }
            return _data;
        }
        
        public bool[] GetBools(byte _mask){
            bool[] _values = new bool[8];
            for(int i = 0; i < 8; i++){
                if((_mask& (1<<i)) !=0){
                    _values[i] = true;
                }else{
                    _values[i] = false;
                }
            }
            return _values;
        }
        
        public byte WriteBools(bool[] _data){
            byte _byte = 0;
                for(int i = 0; i < 8; i++){
                    if(_data[i]){
                        _byte = System.Convert.ToByte(( _byte | (1<<i)));
                    }
                }
            return _byte;
        }
    }
    

    你可以在这里找到完整的要点https://gist.github.com/namusanga/abecca458a3a15ca9bfa6fcdd7953e31

    【讨论】:

      【解决方案3】:

      其他静态函数版本

      /// <summary>
      /// Convert Byte Array To Bool Array
      /// </summary>
      /// <param name="bytes"></param>
      /// <returns></returns>
      public static bool[] ConvertByteArrayToBoolArray(byte[] bytes)
      {
          System.Collections.BitArray b = new System.Collections.BitArray(bytes);
          bool[] bitValues = new bool[b.Count];
          b.CopyTo(bitValues, 0);
          Array.Reverse(bitValues);
          return bitValues;
      }
      
      /// <summary>
      /// Packs a bit array into bytes, most significant bit first
      /// </summary>
      /// <param name="boolArr"></param>
      /// <returns></returns>
      public static byte[] ConvertBoolArrayToByteArray(bool[] boolArr)
      {
          byte[] byteArr = new byte[(boolArr.Length + 7) / 8];
          for (int i = 0; i < byteArr.Length; i++)
          {
              byteArr[i] = ReadByte(boolArr, 8 * i);
          }
          return byteArr;
      }
      

      【讨论】:

        【解决方案4】:

        这是我将如何实现的。

        要将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 的布尔数组:

        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;
        }
        

        【讨论】:

          猜你喜欢
          • 2022-06-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-04
          • 2015-02-23
          • 1970-01-01
          • 2014-12-20
          相关资源
          最近更新 更多