BinaryWriterWith7BitEncoding & BinaryReaderWith7BitEncoding

Posted by Tim on Stack Overflow See other posts from Stack Overflow or by Tim
Published on 2010-06-17T14:02:42Z Indexed on 2010/06/17 14:33 UTC
Read the original article Hit count: 326

Filed under:

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 ?

© Stack Overflow or respective owner

Related posts about c#