Unusual Integer encoding to bytes - what scheme is this?

后端 未结 2 572
夕颜
夕颜 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
    

提交回复
热议问题