3

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();
    }
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • 1
    Why are your numbers in strings to begin with? If this is related to http://stackoverflow.com/questions/14095943/how-to-generate-desired-size-example-8096-long-bit-hash-codes-c-sharp , please be aware that handling numbers as strings is wildly inefficient. – Matti Virkkunen Dec 31 '12 at 01:12
  • @MattiVirkkunen thanks for warning. actually this is kind of hashing and hash checking operation. so we can say something else. – Furkan Gözükara Dec 31 '12 at 01:33
  • Also i tried the answers with int64 but still too big number. – Furkan Gözükara Dec 31 '12 at 01:35

5 Answers5

3

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.

Community
  • 1
  • 1
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
2

You have to convert the string to numbers first, you can use "Convert.ToInt32(String, Int32)", the second parameter lets you specify the base:

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

int one = Convert.ToInt32(sr1, 2);
int two = Convert.ToInt32(sr2, 2);

int result = one & two;

hope it helps.

AngelCastillo
  • 2,385
  • 2
  • 18
  • 26
2

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');
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • ok your solution works but after you did & operation how will you convert that big integer to the bit array again :D – Furkan Gözükara Dec 31 '12 at 13:02
  • @MonsterMMORPG - search should give several approache - I've seen several solutions recently on SO. I'd convert to bytes, than join string representation of each byte + pad with "0" as necessary. – Alexei Levenkov Jan 01 '13 at 01:50
  • yes i need those. but after all would your solution (including convert to bytes then join string each byte with pad 0) or my dirty solution work faster ? 5000 characters long :) – Furkan Gözükara Jan 01 '13 at 02:06
1

You can't do bitwise operations on a string in the way you intend. There are interesting things you can do with bitwise operations on strings with other goals, like changing their case, but I think this is what you want:

// Convert the string to an integer

int foo = Convert.ToInt32(sr1, 2);
int bar = Convert.ToInt32(sr2, 2);

// Perform binary styff
int result = foo & bar;

// Convert back to a string, if you want
string resultStr = result.ToString();
Charles Burns
  • 10,310
  • 7
  • 64
  • 81
1

I like Alexei's BigInteger solution, but it does require .NET 4.0 minimum. If for some reason you can't use that, then another option is to use the BitArray class, which has been available since .NET 1.1. Unfortunately, there is no method built-in to BitArray to parse a binary string, so you have to do that manually, similar to Alexei's solution.

Another option is a class I wrote called BoolArray which does a lot of the same things as BitArray, but does have a method to parse binary strings - use the static BoolArray.FromBinaryString method:

BoolArray bin = BoolArray.FromBinaryString("1001011000111010101");   // etc

Here is the BoolArray source code. Note, however, that it isn't quite complete, and isn't fully tested either, but I'm not immediately aware of any bugs.

EDIT: I noticed after pasting the original link that the code used a function provided in a different class of my "Utils" library, and wouldn't have compiled directly. I've updated the link to provide this class in the code as well... hopefully that was the only case, but if not let me know and I can fix.

Michael Bray
  • 14,998
  • 7
  • 42
  • 68