Search code examples
c#redisbooksleeve

How do I return a C# bitarray from Redis with Booksleeve


I may be approaching this all wrong, but I would like to use a REDIS bitmap to track activity within my application. I have a piece of code like the following:

 using (var conn = new RedisConnection("localhost"))
        {
            conn.Open();

            var b1 = conn.Strings.SetBit(1, "test:2012-07-25", 1, true);
            conn.Wait(b1);

            var b2 = conn.Strings.SetBit(1, "test:2012-07-25", 3, true);
            conn.Wait(b2);


            var arr = conn.Strings.Get(1, "test:2012-07-25");
            conn.Wait(arr);


            BitArray bits = new BitArray(arr.Result);

        }

I can add entries (b1 & b2) without any issue. However, when I attempt to get the bitmap back from the server as a bitarray it does not work correctly (I get a value but the bits that are set are completely incorrect). I assume I am doing something wrong in using the Strings.Get function to attempt to return the bits, but I don't know how else to go about it. The only obvious way to do it would be to make individual calls to getbit for each date I am interested in, but this would seemingly introduce a significant amount of round-trips to the server. Any help would be appreciated!


Solution

  • Sorry folks, the correct result is being returned, I was reading it wrong. There are really two gotchas:

    • The bits are written from right to left. When a byte is returned it will essentially be in the reverse order of what is expected (expected by me at least). So in the above examble. I was sent back a byte that looked like this (the reverse of what I expected)

    [0] false [1] false [2] false [3] false [4] true [5] false [6] true [7] false

    • You need to read in order of bytes. Byte 0 will contain the first 8 bits, 1 the next set of bits, ad infinitum. This is only important to note because of the bit reversal mentioned in point #1. If, in my original example, i had set offset 10 to true in Redis, this would show up in bit position 13. This is because offsets (bits) 0-7 are stored in the first byte and offsets 8-15 are stored in the second byte. Offset 10 is the 3rd stored in the second byte, and since it's reverse we count back from 15,14...13

    I guess the key is actually to reverse the bytes/bits before processing...Hope this helps someone out in the future...