【问题标题】:C# parse non uniform bit sequences from array of bytesC#从字节数组中解析非统一位序列
【发布时间】:2014-11-19 15:49:06
【问题描述】:

问题:有没有更有效的方法将字节数组中的位解析为整数值?如果有,那会是什么?

当前从流中读取数据,数据包由一系列字节组成(保存在字节数组中)。数据在这些字节中被压缩,这样一个值可以跨多个字节(按顺序)传播。构成这些值的位的大小取决于数据包的“类型”(保存在第一个字节的前 5 位(从 MSB 开始)中。例如,

byte[] bytes = {0x73, 0xa4};
// yields: 0111001110100100
// vals:   [ 1 ][  2  ]3[4]

目前我使用的是扩展方法:

public static string ConvertToBinaryString(this byte[] bytes)
{
    return string.Join("", bytes.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')));
}

将字节数组转换为二进制字符串。然后我使用这两种扩展方法之一将二进制字符串转换为 int 或 int 数组:

static readonly Regex IsBinary = new Regex("^[01]{1,32}$", RegexOptions.Compiled);
public static bool TryParseBits(this string toParse, int start, int length, out int intVal)
{
    intVal = -1;
    if (!IsBinary.IsMatch(toParse)) return false;
    if ((start + length + 1) > toParse.Length) return false;
    intVal = Convert.ToInt32(toParse.Substring(start, length), 2);
    return true;
}
public static bool TryParseBits(this string toParse, Queue<int> lengths, out List<int> vals)
{
    vals = new List<int>();
    if (!IsBinary.IsMatch(toParse)) return false;
    var idx = 0;
    while (lengths.Count > 0)
    {
        var l = lengths.Dequeue();
        if ((idx + l) > toParse.Length) return false;
        vals.Add(Convert.ToInt32(toParse.Substring(idx, l), 2));
        idx += l;
    }
    return true;
}

使用示例:

int type;
var success = "0111001110100100".TryParseBits(0, 5, out type);

结果类型 = 14

背景:正在读取的流可以传输高达 12 个数据包/秒。在必须解析字节之前发生了一些预处理,并且在值上发生了重要的后处理。使用 Parallel.ForEach 将数据包分成四个线程。这些值永远不会大于 28 位,因此在转换为 int 时我不用担心符号位。

【问题讨论】:

  • 你的字节数组总是2/4字节吗?它们总是采用 Big Endian 格式吗? (字节 0 是您示例中的 MSB)
  • Big Endian 格式的大小为 56 到 112 个字节。虽然我知道在解析这些字节之前有多少字节。在少数情况下字节数组较大,但我可以轻松地将它们解析到这个范围内。
  • 在您的示例中,前五位是"01110"。这等于 0x0E,而不是 0x07。
  • 很好,更新了...谢谢。

标签: c# parsing bytearray


【解决方案1】:

您尝试过位掩码之类的方法吗?
知道例如第一个 byteArray 的最后 4 位是我们可以做的第一个 val:

byte[] bytes = { 0x73, 0xa4 };
int v1 = bytes[0] & 0x0F;
//second val:
int v2 = bytes[2] & 0xF0;


在涂抹面膜之前,只需将所有东西都存放在啤酒中。

 int total = 0;
 total = total | bytes[0];
 total = total << 8;
 total = total | bytes[1];
 //now the 2 bytes array is stored in a number in our case total will be: 111001110100100
 //after storing apply bit masks as described above:
 // to get the LAST 3 bytes
 int var1 = total & 0x7 //mask with last 3 bytes
 total = total >> 3; //take out last 3 bytes
 int var2 = total & 0x1 //last byte.
 total = total >>1;
 //and so on

【讨论】:

  • 这不起作用,因为指定值的位不一定是每个 8 位。
  • 实际上我的第一遍只是解析每个值所涉及的字节并使用掩码、OR 和 SHIFT。但考虑到所有“类型”的可能性,这很乏味且容易出错……尽管它可能是最高效的。
  • 我添加了一个解析机制来提取你想要的位。让我知道它是否有效
【解决方案2】:

为了完整起见,这是我根据显然已删除的答案提出的。

public static int ParseBits(this byte[] bytes, int start, int length)
{
    // Need to reverse the array to make it usable with BitArray
    Array.Reverse(bytes);
    var ba = new BitArray(bytes);
    var idx = 0;
    var shft = length - 1;
    // Iterate backwards through the bits and perform bitwise operations
    for (var i = start + length - 1; i >= 0; i--)
    {
        idx |= (Convert.ToInt32(ba.Get(i)) << shft);
        shft--;
    }
    return idx;
}

【讨论】:

    【解决方案3】:

    您只需要了解按位运算即可。

    byte[] bytes = {0x73, 0xa4};
    // yields: 0111001110100100
    // vals: [ 1 ][ 2 ]3[4]
    
    int bits = bytes[1] | bytes [0] << 8;
    int v1 = (bits & 0xf800) >> 11;
    int v2 = (bits & 0x07f0) >> 5;
    int v3 = (bits & 0x0008) >> 3;
    int v4 = bits & 0x0007;
    

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2019-01-05
      相关资源
      最近更新 更多