gpt4 book ai didi

c# - BinaryWriterWith7BitEncoding & BinaryReaderWith7BitEncoding

转载 作者:太空宇宙 更新时间:2023-11-03 11:47:22 24 4
gpt4 key购买 nike

先生。 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);
}
}

关于c# - BinaryWriterWith7BitEncoding & BinaryReaderWith7BitEncoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3062292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com