0

I'm trying to write a method in C# that will return the difference between two byte arrays by comparing each byte in the arrays and returning the byte from the second if it is different from the first. I have this so far:

        byte[] b1 = 111;
        byte[] b2 = 105;

        int j = input.Length;

        byte[] differenceByte = new byte[j];

        int diffIndex = 0;

        for (int i = 0; i < j; i++)
        {
            if (originalByte[i] != comparisonByte[i])
                differenceByte[diffIndex++] = comparisonByte[i];
        }

But I was hoping to find a way to replace the if statement comparing the first byte to the second with some bitwise voodoo magic... Is there a way to do this?

A second question is there any other way to optimize this code so that it will run as fast as possible?

I would ultimately like to use this code to compare two strings by converting the strings to and from an array of bytes, so if there is something I should know about in that respect, that would also be helpful.

Thick_propheT
  • 1,003
  • 2
  • 10
  • 29
  • 1
    It would help if you could give us more context of the bigger picture here. Why would you want to convert the strings to bytes, instead of comparing characters, for example? – Jon Skeet May 13 '12 at 19:30
  • 1
    If you're looking for a "string diff," maybe check out [this answer](http://stackoverflow.com/questions/208094/how-to-find-difference-between-two-strings). – Cᴏʀʏ May 13 '12 at 19:32
  • 1
    Are you considering Unicode and multi-byte encodings? Because characters are not bytes, some characters may span to multiple bytes. – Luka Ramishvili May 13 '12 at 19:33
  • You could use the exclusive OR operator: `(originalByte[i] ^ comparisonByte[i] > 0)`. It certainly wouldn't clarify the code. Performance might decrease, but it's worth it for the obfuscation. – HABO May 13 '12 at 19:50
  • @JonSkeet I was converting to bytes because I was thinking there might be a way to use bitwise operators to get what is different between the strings, but I can tell I'm going to have to rethink this thing completely. Thanks for all the suggestions, guys! – Thick_propheT May 13 '12 at 20:30

1 Answers1

1

Equality operators operate on bits.
There is no bitwise voodoo magic that will improve equality operators.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964