semedao <se*****@commun ity.nospamwrote :
Hi , I try the BitArray class to make Xor on 2 byte arrays.
The result was that when I Xor 1with 2 I get 3 which is correct
then Xoring 3 with 1 give me 0 (zero) when it should give me 2 !
but Xoring 3 with 2 give 2 which is correct... (should be 1)
<snip>
Okay, well, let's make your sample code a bit more manageable. There's
no need to pepper the code with conversions and things, when you can do
them once:
using System;
using System.Collecti ons;
class Test
{
static void Main()
{
BitArray ba1 = new BitArray(new int[]{1});
BitArray ba2 = new BitArray(new int[]{2});
BitArray ba3 = ba1.Xor(ba2);
DumpBitArray(ba 3);
DumpBitArray(ba 3.Xor(ba1));
DumpBitArray(ba 3.Xor(ba2));
}
static void DumpBitArray(Bi tArray bitArray)
{
byte[] bytes = new byte[(bitArray.Lengt h+7)/8];
bitArray.CopyTo (bytes, 0);
Console.WriteLi ne (BitConverter.T oString(bytes)) ;
}
}
That prints:
03-00-00-00
00-00-00-00
02-00-00-00
And that demonstrates the problem you're having. Now we can easily add
another couple of lines to look at ba1 and ba2, just to check they
haven't changed at the end
DumpBitArray(ba 1);
DumpBitArray(ba 2);
Now the full dump is:
03-00-00-00
00-00-00-00
02-00-00-00
02-00-00-00
02-00-00-00
ba1 appears to have changed! Given that all we've done is call Xor on
it, we need to consult the documentation for Xor... unfortunately, the
docs don't make it terribly clear, although the example *does* show
that calling Xor on a BitArray changes its contents.
If you don't want to change the contents, you could either call Clone
on the original or create a new one with new BitArray (oldBitArray).
For instance:
BitArray ba3 = new BitArray(ba1).X or(ba2);
So the documentation could certainly be a lot clearer, but the method
does work.
--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too