c# - 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
解决方案
这使用 linq 来做到这一点:
var shorts = bools.Select(s => s ? (short)1 : (short)0).ToArray();
推荐阅读
- python - 在 numpy 数组上应用“同时”多个条件
- gtk - jhbuild build 得到了我的系统上未安装的错误介子版本
- laravel - Laravel:一个模型中的多个表
- mysql - 错误:在 xampp 中启动 mysql 服务后 MySQL 意外关闭
- mapbox - 使用 Mapbox GL JS 根据单击的图层设置不同的弹出窗口样式
- python - 使用 Pandas 从对象中解析 DateTime
- sqlite - 数据库磁盘映像格式错误
- matplotlib - matplotlib 后端 pgf 版本未知
- c++ - 添加有符号和无符号整数
- java - 通过重启在树莓派上启动一个 jar