1

I am trying to flip the bits of an unsigned 32-bit integer and output the resultant integer. The following is my code.

int numberOfTries = Convert.ToInt32(Console.ReadLine());
        for (int i = 0; i < numberOfTries; i++)
        {
            uint input = Convert.ToUInt32(Console.ReadLine());
            byte[] bInput = BitConverter.GetBytes(input);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bInput);
            byte[] result = bInput;

            BitArray b = new BitArray(new byte[] { result });
            b.Not();
            uint res = 0;
            for (int i2 = 0; i2 != 32; i2++)
            {
                if (b[i2])
                {
                    res |= (uint)(1 << i2);
                }
            }

            Console.WriteLine(res);
        }

However, the compiler complains that "Cannot implicitly convert type 'byte[]' to 'byte' " on the line where I declare BitArray b. I have declared it as a byte[] and have no idea why this error is being thrown.

1 Answer 1

4

result is already a byte[], so do this instead:

BitArray b = new BitArray(result);

The part that's actually causing the problem is this:

new byte[] { result }

The reason for this is because the array initializer needs to take expressions that are compatible with the element type of the array (here, byte). From 12.6 Array Initializers:

For a single-dimensional array, the array initializer must consist of a sequence of expressions that are assignment compatible with the element type of the array.

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

Comments

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.