ZoOl007
ZoOl007

Reputation: 417

checksum calculation using ArraySegment<byte>

I have issue with the following method - I don't understand why it behaves the way it does

private static bool chksumCalc(ref byte[] receive_byte_array)
{
    Console.WriteLine("receive_byte_array -> " + receive_byte_array.Length); //ok,151 bytes in my case
    ArraySegment<byte> segment = new ArraySegment<byte>(receive_byte_array, 0, 149);
    Console.WriteLine("segment # -> " + segment.Count); //ok,149 bytes

    BitArray resultBits = new BitArray(8); //hold the result
    Console.WriteLine("resultBits.Length -> " + resultBits.Length); //ok, 8bits
    //now loop through the 149 bytes
    for (int i = segment.Offset; i < (segment.Offset + segment.Count); ++i)
    {
        BitArray curBits = new BitArray(segment.Array[i]);
        Console.WriteLine("curBits.Length -> " + curBits.Length); //gives me 229 not 8?
        resultBits = resultBits.Xor(curBits);
    }

    //some more things to do  ... return true...
    //or else
    return false;
}

I need to XOR 149 bytes and I don't understand why segment.Array[i] doesn't give me 1 byte. If I have array of 149 bytes if I use for example segment.Array[1] it has to yield the 2nd byte or am I that wrong? Where does the 229 come from? Can someone please clarify? Thank you.

Upvotes: 0

Views: 267

Answers (1)

user47589
user47589

Reputation:

This is the constructor you're calling: BitArray(int length)

Initializes a new instance of the BitArray class that can hold the specified number of bit values, which are initially set to false.

If you look, all of the constructors for BitArray read like that. I don't see why you need to use the BitArray class at all, though. Just use a byte to store your XOR result:

private static bool chksumCalc(ref byte[] receive_byte_array)
{
    var segment = new ArraySegment<byte>(receive_byte_array, 0, 149);
    byte resultBits = 0;
    for (var i = segment.Offset; i < (segment.Offset + segment.Count); ++i)
    {
        var curBits = segment.Array[i];
        resultBits = (byte)(resultBits ^ curBits);
    }

    //some more things to do  ... return true...
    //or else
    return false;
}

I don't think you need the ArraySegment<T> either (not for the code presented), but I left it as is since it's beside the point of the question.

Upvotes: 3

Related Questions