Matias Cicero
Matias Cicero

Reputation: 26281

C# - Converting from bits to Int32 generates wrong value

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?

Upvotes: 0

Views: 491

Answers (1)

Jashaszun
Jashaszun

Reputation: 9270

The bit order is incorrect. -268435456 as a 32-bit integer is 11110000 00000000 00000000 00000000, which, as you can see, is exactly opposite what you wanted.

Just reverse your numberBits array before converting it to an Int32.

Alternatively, you could make numberData have the correct order and then never do any reversing.

Your code is working exactly how you wrote it. In numberData[0] is 0, numberData[1] is 0, ..., and numberData[31] is 1. This will cause bit 0 of your result to be 0, bit 1 to be 0, ..., and bit 31 to be 1.

Upvotes: 3

Related Questions