【问题标题】:Unusual Integer encoding to bytes - what scheme is this?不寻常的整数编码到字节 - 这是什么方案?
【发布时间】:2015-10-08 16:48:55
【问题描述】:

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

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

【问题讨论】:

  • 你确定这是编码吗?看起来有人在重新排列 dwords 中的字节,但做得不太对。
  • @GSerg 来自数据源的十六进制转储始终采用这种模式,因此我觉得这是一种编码形式
  • @GSerg 这是用于编码每种情况下遵循的二进制有效负载长度的模式。我的手动长度计算是准确的,因此我认为这是一些整数(长度)编码模式

标签: .net vb.net binary integer


【解决方案1】:

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

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

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

【讨论】:

  • 您能否举个例子,特别是转换128和256。为什么它以80开头?
  • 我添加了一个重要的例子。您看到 80 仅仅是因为设置了高位,它编码了 7 位 0。如果您需要代码,则只需复制/粘贴框架源代码。解码器is here.
  • 刚刚看到你的例子。那么,在某些情况下,我们是否必须在 .net 中手动处理才能获得前导 80 的预期输出?
  • 您提供的链接是针对 BinaryReader.cs 我查看了 binaryWriter.cs referencesource.microsoft.com/#mscorlib/system/io/… 的。当您尝试执行 cbyte(value) 时,等效的 VB.net 失败,值 >255。
  • 当然,这在 VB.NET 中无效,仅在 C# 中并且只有在禁用溢出检查时才有效。您必须使用 CByte(value And &HFF)。如果您对此有更多疑问,请单击该按钮。
【解决方案2】:

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

    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

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多