开发者

BinaryWriterWith7BitEncoding & BinaryReaderWith7BitEncoding

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 sig开发者_如何学Gonatures: 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 ?


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);
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜