如何将布尔数组转换为字节,再转换为整数?
问题描述:
我想将布尔数组(例如{true,true,false})转换为字节(00000110)
并转换为整数后将为6.
我将如何用C#编写代码?感谢您的回答...
I want to convert a bool array (for example {true, true, false} ) to a byte (00000110)
and after converting to integer, it would be 6.
How would I code this in C#? Thanks for answering...
答
为什么要经过一个字节?您可以直接前往uint.不幸的是C#/.Net没有布尔值,所以我不知道有什么比
更好的方法了.
Why go via a byte? You can go straight to uint. Unfortunately C#/.Net doesn''t have bit booleans so I am not aware of a better approach than
uint BoolArrayToInt(bool[] bits){
if(bits.Length > 32) throw new ArgumentException("Can only fit 32 bits in a uint");
uint r = 0;
for(int i = 0; i < bits.Length; i++) if(bits[i]) r |= 1 << (bits.Length - i);
return r;
}
看看BitArray
类,您也可以看一下我的文章,该文章将在此处压缩输出整数:BitArray的字对齐混合(WAH)压缩 [ ^ ]
Take a look at the BitArray
class, you can also look at my article which will compress the output integers here : Word Aligned Hybrid (WAH) Compression for BitArrays[^]