0

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?

2
  • I don't think there's an overflow. BitArray has a total of 32 bits, which are being copied to a byte[] of size 4 Commented Oct 24, 2014 at 17:22
  • Note: this is a very long winded way of creating an integer from bits. Much better ways of doing this exist (which also don't suffer from the "endianness" issue) Commented Oct 24, 2014 at 17:35

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I have reversed numberData and now number is returning 251658240 :(
@MatiCicero I've just tried your code, reversing the bits (1,1,1,1,0,0,....,0,0), and the answer comes out as 15...
My bad, it's in fact returning 15. This solution is correct
Confirmed. I did an Array.Reverse(numberData); and it does come out as 15.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.