Convert 64-bit array to Int64 or ulong C #

I have an int bit array (the length is always 64), like:

  1110000100000110111001000001110010011000110011111100001011100100 

and I want to write it in a single Int64 variable (or ulong?). How to do it?

I tried to create a BitArray and then get an int , but it throws a System.ArgumentException , on the CopyTo line:

 private static Int64 GetIntFromBitArray(BitArray bitArray) { var array = new Int64[1]; bitArray.CopyTo(array, 0); return array[0]; } 
+5
source share
1 answer

This is because, as stated in the documentation ,

The specified array must be of a compatible type. Only bool, int, and byte array types are supported.

So you can do something like this: (not verified)

 private static long GetIntFromBitArray(BitArray bitArray) { var array = new byte[8]; bitArray.CopyTo(array, 0); return BitConverter.ToInt64(array, 0); } 

Looking at the implementation of BitArray.CopyTo , it would be faster to copy the bit to int[] (and then build a long of its two halves), which could look something like this: (also not tested)

 private static long GetIntFromBitArray(BitArray bitArray) { var array = new int[2]; bitArray.CopyTo(array, 0); return (uint)array[0] + ((long)(uint)array[1] << 32); } 

Drops uint to prevent sign expansion.

+4
source

All Articles