Unusual Integer encoding to bytes - what scheme is this?

后端 未结 2 567
夕颜
夕颜 2020-12-11 21:32

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


        
相关标签:
2条回答
  • 2020-12-11 22:18

    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
    
    0 讨论(0)
  • 2020-12-11 22:20

    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

    0 讨论(0)
提交回复
热议问题