I am trying to convert an array of int values (each value representing a bit) to its representation as an Int32 object.
I have the following code:
//0000_0000_0000_0000_0000_0000_0000_1111 = 15
int[] numberData = new int[]
{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 1
};
//We convert our int[] to a bool[]
bool[] numberBits = numberData.Select(s => { return s == 0 ? false : true; }).ToArray();
//We generate a bit array from our bool[]
BitArray bits = new BitArray(numberBits);
//We copy all our bits to a byte[]
byte[] numberBytes = new byte[sizeof(int)];
bits.CopyTo(numberBytes, 0);
//We convert our byte[] to an int
int number = BitConverter.ToInt32(numberBytes, 0);
However, after executing this code, the value of number is -268435456.
Why does this happen?