不寻常的整数编码为字节 - 这是什么方案?

Unusual Integer encoding to bytes - what scheme is this?

使用什么整数编码方案来实现以下内容,我们如何在.Net中做到这一点:

127 = 7F
128 = 8001
255 = FF01
256 = 8002
500 = F403

不太确定它有正式名称,它是一个 7 位编码。它是一种可变长度编码,如果后面跟着另一个字节,则设置一个字节的高位。字节顺序是小端。

.NET Framework uses it,Write7BitEncodedInt() 方法。由 BinaryWriter.WriteString() 方法使用,它节省了 space,因为大多数实用的字符串少于 128 个字符。

所以 F403 => 03F4 => |0000011|1110100| => |00000001|11110100| => 0x1F4 == 500

已解决。我希望这对其他人有帮助。

    Dim o = {127, 128, 255, 256, 500}

    For Each i As Integer In o
        Console.WriteLine("{0} = {1}", i, Write(i))
    Next

Function Write(value As Short) As String
    Dim a = New List(Of Byte)

    ' Write out an int 7 bits at a time.  The high bit of the byte, 
    ' when on, tells reader to continue reading more bytes.
    Dim v = CShort(value)
    ' support negative numbers
    While v >= &H80
        a.Add(CByte((v And &HFF) Or &H80))
        v >>= 7
    End While

    a.Add(CByte((v And &HFF)))

    Return B2H(a.ToArray)
End Function

Function B2H(b() As Byte) As String
    Return BitConverter.ToString(b).Replace("-", "")
End Function

结果:

127 = 7F
128 = 8001
255 = FF01
256 = 8002
500 = F403