Unusual Integer encoding to bytes - what scheme is this?

时光怂恿深爱的人放手 提交于 2020-01-28 02:44:26

问题


What Integer encoding scheme is used to achieve the following, and how can we do this in .Net:

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

回答1:


Not so sure it has an official name, it is a 7-bit encoding. It is a variable length encoding, the high bit of a byte is set if another byte follows. Byte order is little-endian.

The .NET Framework uses it, Write7BitEncodedInt() method. Used by the BinaryWriter.WriteString() method, it saves space since most practical strings have less than 128 characters.

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




回答2:


SOLVED. I Hope this helps someone else.

    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

Result:

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


来源:https://stackoverflow.com/questions/31501672/unusual-integer-encoding-to-bytes-what-scheme-is-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!