如何将布尔数组转换为字节,再转换为整数? [英] How to convert a bool array to a byte, and further to an integer?

查看:1354
本文介绍了如何将布尔数组转换为字节,再转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将布尔数组(例如{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[^]


这篇关于如何将布尔数组转换为字节,再转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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