先生。 Ayende 在他的 latest blog post about an implementation of a queue 中写道.在帖子中,他使用了两个神奇的文件:BinaryWriterWith7BitEncoding 和 BinaryReaderWith7BitEncoding
BinaryWriterWith7BitEncoding
int和long都可以写吗?使用以下方法签名:void WriteBitEncodedNullableInt64(long? value)
& void Write7BitEncodedInt(int value)
和
BinaryReaderWith7BitEncoding
可以读取使用以下方法签名写入的值:long? ReadBitEncodedNullableInt64()
和 int Read7BitEncodedInt()
到目前为止,我只找到了一种读取 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));
}
我不太擅长字节移位 - 有人知道如何读写 7BitEncoded long 吗?并写入 int ?
下面是这样的写法:
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);
}
}
我是一名优秀的程序员,十分优秀!