使用什么整数编码方案来实现以下目标,以及如何在.Net中执行此操作:
127 = 7F
128 = 8001
255 = FF01
256 = 8002
500 = F403
答案 0 :(得分:7)
不确定它是否有正式名称,它是一个7位编码。它是一个可变长度编码,如果跟随另一个字节,则设置一个字节的高位。字节顺序是小端的。
.NET Framework uses it,Write7BitEncodedInt()方法。由BinaryWriter.WriteString()方法使用,它节省了空间,因为大多数实际字符串的字符少于128个。
所以F403 => 03F4 => | 0000011 | 1110100 | => | 00000001 | 11110100 | => 0x1F4 == 500
答案 1 :(得分:0)
解决。我希望这可以帮助别人。
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