How can I convert BitArray
to a single int
?
4 Answers
private int getIntFromBitArray(BitArray bitArray)
{
if (bitArray.Length > 32)
throw new ArgumentException("Argument length shall be at most 32 bits.");
int[] array = new int[1];
bitArray.CopyTo(array, 0);
return array[0];
}
-
1Wow... I didn't think this would work to put all the bits into one integer value - but it does! Nov 19, 2011 at 11:27
-
4Refer this: codereview.stackexchange.com/questions/3796/… Need to check the length of bitArray Aug 2, 2012 at 6:41
-
5Nice trick, however it could have issues related to byte order (endianess) on various platforms. It would be better to use
byte
array as destination for bit array copy and useBitConverter.ToInt32(array, 0)
method afterwards. Feb 8, 2019 at 12:09
This version:
- works for up to 64 bits
- doesn't rely on knowledge of BitArray implementation details
- doesn't needlessly allocate memory
- doesn't throw any exceptions (feel free to add a check if you expect more bits)
- should be more than reasonably performant
Implementation:
public static ulong BitArrayToU64(BitArray ba)
{
var len = Math.Min(64, ba.Count);
ulong n = 0;
for (int i = 0; i < len; i++) {
if (ba.Get(i))
n |= 1UL << i;
}
return n;
}
-
2Can you explain how this is better than the accepted solution from 7 years ago? Is it faster, more accurate, better at error handling, using less memory?– nvoigtJul 20, 2018 at 9:12
private int getIntFromBitArray(BitArray bitArray)
{
int value = 0;
for (int i = 0; i < bitArray.Count; i++)
{
if (bitArray[i])
value += Convert.ToInt16(Math.Pow(2, i));
}
return value;
}
-
Can you explain why the OP should use this over the other solution? Sep 27, 2012 at 4:47
-
1@AustinHenley I wrote this solution for debug purposes. I can step through my code to see how the number is being converted. I'm not sure if you can do that with the first solution. Aug 1, 2013 at 18:34
-
1It's also interesting to know that the first solution is not available on WinRT (probably because of the way ARM processors save the numbers) Sep 17, 2013 at 10:19
-
1
-
5The .NET Core stack may not have BitArray.CopyTo. That being said, why not
1 << i
rather thanConvert.ToInt16(Math.Pow(2, i))
? Feb 11, 2017 at 19:39
Reffering to this post (#43935747). A value X is short tpe whic I set two bits (6 and 10) like below: short X=1;
var result = X;
var bitsToSet = new [ ] { 5,9 };
foreach ( var bitToSet in bitsToSet )
{
result+=( short ) Math.Pow ( 2,bitToSet );
}
string binary = Convert.ToString ( result,2 );
Now I would like to read the specific all bits from Value X and put it in to an array or a bit type like bool Val1= bit1, bool Val2=bit2....
I am a newbie and I think it is pretty simple for you guyes..
-
OK but you should make it
|=
and(short)(1 << bitToSet)
to make it more obvious at a glance. It's not like this code is incomprehensible, but it relies on the combination of some "carefully chosen coincidences" instead of just obviously doing the right thing.– haroldMay 12, 2017 at 13:43