Search code examples
c#stringbit-manipulationlogical-operatorsoperation

Bitwise operations on strings - 1440 characters length


How can i make bitwise operations on strings at c#

example

string sr1="0101110";
string sr2="1101110";

sr1 & sr2="0101110";

or

sr1 | sr2="1101110";

How can i make such comparison ?

Notice string lengths are fixed 1440 characters

Here my dirty solution

    private string compareBitWiseAnd(string sr1, string sr2)
    {
        char[] crArray1 = sr1.ToCharArray();
        char[] crArray2 = sr2.ToCharArray();
        StringBuilder srResult = new StringBuilder();

        for (int i = 0; i < crArray1.Length; i++)
        {
            if (crArray1[i] == crArray2[i])
            {
                srResult.Append(crArray1[i]);
            }
            else
            {
                srResult.Append('0');
            }
        }

        return srResult.ToString();
    }

    private string compareBitWiseOr(string sr1, string sr2)
    {
        char[] crArray1 = sr1.ToCharArray();
        char[] crArray2 = sr2.ToCharArray();
        StringBuilder srResult = new StringBuilder();

        for (int i = 0; i < crArray1.Length; i++)
        {
            if (crArray1[i] == '1' || crArray2[i] == '1')
            {
                srResult.Append("1");
            }
            else
            {
                srResult.Append('0');
            }
        }

        return srResult.ToString();
    }

Solution

  • BigInteger is the type you are looking for. It also have BitwiseOr.

    If you really need to stick with strings it is not very hard to compute bitwise operations on character-by-character basis... but I'd avoid doing it if possible.

    And here is a question on how to construct BigInteger from string of any base - BigInteger Parse Octal String?

    var bitString = "10101";
    BigInteger value = bitString.Aggregate(new BigInteger(), (b, c) => b * 2 + c - '0');