MrVoid
MrVoid

Reputation: 709

C# Bitshift & Bitwise operation

I am trying to find the faster approach for the following problem.

I have 2 int arrays representing bits, here an example of an 8 positions one

int[] intArray1 = new[] {1, 1, 1, 0, 1, 1, 0, 1};
int[] intArray2 = new[] {0, 1, 0, 0, 1, 0, 0, 1};

The number of bits in the arrays could be 8, 32, 64 and 64+

So I should be able to create an algorithm that handles any kind of input, shifts bits for each and applies logical operations between both arrays in the faster way possible.

After a bit of research, I thought of casting the int array to a bool array and create a BitArray using the bool array, because BitArray has a constructor that supports bools as bits and it has built-in bit-wise operations.

bool[] boolArray = intArray.Select(s => s.Equals(1)).ToArray();
BitArray bitArray = new BitArray(boolArray);

However it does not support built-in bit-shifting, it needs to be done iterating, loosing the whole performance point that I am trying to achieve.

I could use int32 and int64 but that solution will not work for sizes larger than 64 bits.

Kind Regards

Upvotes: 1

Views: 1142

Answers (1)

agillgilla
agillgilla

Reputation: 889

Why not just use a BigInteger?

You can use this method to convert a string to a BigInteger:

public static BigInteger BinToDec(string value)
{
    // BigInteger can be found in the System.Numerics dll
    BigInteger res = 0;

    // I'm totally skipping error handling here
    foreach(char c in value)
    {
        res <<= 1;
        res += c == '1' ? 1 : 0;
    }

    return res;
}

Or if you want to stick with your int array and convert that to a BigInteger:

public static BigInteger BitArrayToBigDecimal(int[] bitIntArr) {
    // BigInteger can be found in the System.Numerics dll
    BigInteger res = 0;

    // I'm totally skipping error handling here
    foreach(int i in bitIntArr) {
        res <<= 1;
        res += i == 1 ? 1 : 0;
    }
    return res;
}

You can bit shift them, too. Like this:

var foo = BinToDec("11101101");

BigInteger fooShifted = foo >> 4;

var bar = BitArrayToBigDecimal(new[] {1, 1, 1, 0, 1, 1, 0, 1});

BigInteger barShifted = bar >> 4;

Let me know if you have any questions.

Upvotes: 1

Related Questions