2

Mr. Ayende wrote in his latest blog post about an implementation of a queue. In the post he's using two magical files: BinaryWriterWith7BitEncoding & BinaryReaderWith7BitEncoding

BinaryWriterWith7BitEncoding can write both int and long? using the following method signatures: void WriteBitEncodedNullableInt64(long? value) & void Write7BitEncodedInt(int value)

and

BinaryReaderWith7BitEncoding can read the values written using the following method signatures: long? ReadBitEncodedNullableInt64() and int Read7BitEncodedInt()

So far I've only managed to find a way to read the 7BitEncodedInt:

protected int Read7BitEncodedInt()
{
    int value = 0;
    int byteval;
    int shift = 0;
    while(((byteval = ReadByte()) & 0x80) != 0)
    {
        value |= ((byteval & 0x7F) << shift);
        shift += 7;
    }
    return (value | (byteval << shift));
}

I'm not too good with byte shifting - does anybody know how to read and write the 7BitEncoded long? and write the int ?

1
  • If I understand it correctly, this is pretty much the same as what protobuf uses; those versions are a bit... "optimised", but I'll try to simplify. And for info, it makes writing a lot easier if you treat it as unsigned ;p Commented Jun 17, 2010 at 14:25

1 Answer 1

2

Here's something like the write:

    static void Write7BitEncodedInt32(Stream dest, int value)
    {
        Write7BitEncodedUInt32(dest, (uint) value);
    }
    static void Write7BitEncodedUInt32(Stream dest, uint value)
    {
        if(value < 128) { dest.WriteByte((byte)value); return;}
        while(value != 0)
        {
            byte b = (byte) (value & 0x7F);
            value >>= 7; // since uint, we'll eventually run out of 1s
            if (value != 0) b |= 0x80; // and there's more
            dest.WriteByte(b);
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Fantastic! Do you also have a solution to the 2nd part of the question with the nullable long?
@Tim - well, long is virtually identical; the only change is ulong instead of uint etc. With Nullable<T>, it comes down to "what do I write if it is null?" - only you can answer that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.