How can I convert BitArray to single int?
54,060
Solution 1
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];
}
Solution 2
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;
}
Solution 3
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;
}
Author by
Vlad Omelyanchuk
Updated on July 09, 2022Comments
-
Vlad Omelyanchuk almost 2 years
How can I convert
BitArray
to a singleint
?-
Brandon Boone about 13 yearsBitArray to int Array or literally a BitArray to a single integer?
-
-
codekaizen over 12 yearsWow... I didn't think this would work to put all the bits into one integer value - but it does!
-
coder_bro over 11 yearsRefer this: codereview.stackexchange.com/questions/3796/… Need to check the length of bitArray
-
Austin Henley over 11 yearsCan you explain why the OP should use this over the other solution?
-
K4KNOWLEDGE over 10 years@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.
-
tec-goblin over 10 yearsIt's also interesting to know that the first solution is not available on WinRT (probably because of the way ARM processors save the numbers)
-
Mike Christiansen over 9 yearsI have to use this because its not available on ARM.
-
ChristopheD about 7 yearsThe .NET Core stack may not have BitArray.CopyTo. That being said, why not
1 << i
rather thanConvert.ToInt16(Math.Pow(2, i))
? -
harold almost 7 yearsOK 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. -
nvoigt almost 6 yearsCan 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?
-
Jozef Benikovský about 5 yearsNice 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.