INT转换为位阵列中的.NET [英] Convert int to a bit array in .NET
本文介绍了INT转换为位阵列中的.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么能转换将int位数组?
How can I convert an int to a bit array?
如果我如有一个int的值3我想要一个数组,具有长度为8,并且看起来像这样:
If I e.g. have an int with the value 3 I want an array, that has the length 8 and that looks like this:
0 0 0 0 0 0 1 1
每个这些号码是在具有尺寸8的阵列在一个单独的时隙。
Each of these numbers are in a separate slot in the array that have the size 8.
推荐答案
要转换INTX
int x = 3;
一种方法,通过控制在INT:
One way, by manipulation on the int :
string s = Convert.ToString(x, 2); //Convert to binary in a string
int[] bits= s.PadLeft(8, '0') // Add 0's from left
.Select(c => int.Parse(c.ToString())) // convert each char to int
.ToArray(); // Convert IEnumerable from select to Array
另外,通过使用BitArray类 -
Alternatively, by using the BitArray class-
BitArray b = new BitArray(new byte[] { x });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();
这篇关于INT转换为位阵列中的.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文