首页 > 解决方案 > C# bool array 转换短数组

问题描述

如何使不规则bool[]short[]

每个真的有点

例如:

bool[] bools = new []{true,true};

或者:

bool[] bools = new bool[]{true,false,true,false,...};
public static short[] BoolArrayToShortArray(bool[] bools)
{
    
}

我之前试过,但是Bitconverter.ToInt6()需要两个字节

bool[] bools=new bool[]{true,true,true,false,true,false};
List<bool> list=new List<bool>();
list.AddRange(bools);
int ints= bools.Length%16;
for(int i=0;i<16-ints;i++)
    {
        list.Add(false);
     }
     BitArray bits=new BitArray(list.ToArray());
     byte[] bytes= ToByteArray(bits);
     short[] shorts=new short[bytes.Length%16];
     for(int i=0;i<bytes.Length%16;i++)
     shorts[i]= BitConverter.ToInt16(bytes);

true=bit

标签: c#

解决方案


这使用 linq 来做到这一点:

var shorts = bools.Select(s => s ? (short)1 : (short)0).ToArray();

推荐阅读