Bitwise operations on strings - 1440 characters length

MonsterMMORPG picture MonsterMMORPG · Dec 31, 2012 · Viewed 7.2k times · Source

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();
    }

Answer

Robert Harvey picture Robert Harvey · Dec 31, 2012

Convert to actual bits first, and then do the bitwise comparison.

int num1 = Convert.ToInt32(sr1, 2);
int num2 = Convert.ToInt32(sr2, 2);

int result = num1 & num2;

Use this if you want to get a binary string from the result.