How can I convert an int to an array of bool?
How can I convert an int to an array of bool (representing the bits in the inte开发者_StackOverflow中文版ger)? For example:
4 = { true, false, false }
7 = { true, true, true }
255 = { true, true, true, true, true, true, true, true }
An int
should map nicely to BitVector32
(or BitArray
)
int i = 4;
var bv = new BitVector32(i);
bool x = bv[0], y = bv[1], z = bv[2]; // example access via indexer
However, personally I'd just use shifts (>>
etc) and keep it as an int
. The bool[]
would be much bigger
You can use the BitArray.
var bools = new BitArray(new int[] { yourInt }).Cast<bool>().ToArray();
Int32 number = 10;
var array = Convert.ToString(number, 2).Select(s => s.Equals('1')).ToArray();
--Edit--
Using extension method:
public static class Int32Extensions
{
public static Boolean[] ToBooleanArray(this Int32 i)
{
return Convert.ToString(i, 2 /*for binary*/).Select(s => s.Equals('1')).ToArray();
}
}
Usage:
var boolArray = number.ToBooleanArray();
You can do this as a two-step process, first convert the integer to a binary (base 2) string representation using Convert.ToString
and then iterate over that string to populate a BitArray
.
For example:
int someInt = 7;
string binaryString = Convert.ToString(someInt, 2);
BitArray bitArray = new BitArray(binaryString.Length);
for (int i = 0; i < bitArray.Length; i++)
{
bitArray[i] = (binaryString[i] == '1');
}
public static bool[] Convert(int[] input, int length)
{
var ret = new bool[length];
var siz = sizeof(int) * 8;
var pow = 0;
var cur = 0;
for (var a = 0; a < input.Length && cur < length; ++a)
{
var inp = input[a];
pow = 1;
for (var i = 0; i < siz && cur < length; ++i)
{
ret[cur++] = inp > 0 ? (inp & pow) != 0 : (inp & pow) == 0;
pow *= 2;
}
}
return ret;
}
You can use the BitArray
to easily get a collection of booleans from a number:
var b = new BitArray(new int[] { 255 });
However, it will use all the bits in the value, so the above will get you a BitArray
with the length 32 as the int
data type is 32 bits.
You can create a BitArray
from bytes, which would give you eight booleans from each byte:
var b = new BitArray(new byte[] { 255 });
You can get an array with only the significant bits by skipping the leading falses:
bool[] b = new BitArray(42).Cast<bool>().SkipWhile(x => !x).ToArray();
精彩评论