【问题标题】:Converting BitArray to Byte将位数组转换为字节
【发布时间】:2019-12-13 19:57:45
【问题描述】:

我有一个将BitArray 值转换为byte[] 值的代码。我也从 stackoverflow 获得了代码。

代码很好用,只是有一部分没看懂。

当代码使用BitArray.CopyTo()BitArray 复制到Byte 时,byte 读数按LSB 顺序

有人能帮我理解为什么转换后的字节是 LSB 顺序吗?

strBit (is a string value that consists of 1/0)
byte[] myByte = new byte[50];

List<string> list = Enumerable.Range(0, strBit.Length / 8)
    .Select(i => strBit.Substring(i * 8, 8))
    .ToList();

for (int x = 0; x < list.Count; x++)
{
    BitArray myBitArray = new BitArray(list[x].ToString().Select(c => c == '1').ToArray());
    myBitArray.CopyTo(myByte, x);
}

示例输出:

  strBit[0] = 10001111  (BitArray)

当转换为字节时:

  myByte[0] = 11110001 (Byte) (241/F1)

【问题讨论】:

  • 因为您必须选择一些编码,而 .NET Framework 更喜欢一个/发送者发送这个?
  • 我应该在哪里检查那部分?还是 .Net 框架中字节数据类型的默认值?抱歉,我是新手
  • 你不得不猜测对方正在使用的编码。 joelonsoftware.com/2003/10/08/… 有时您可以获得提示,甚至可以找到您想要的提示。我的建议是避免下降到二进制级别,让别人的代码为你处理这个问题。 |我将二进制表示视为时区 - 只需询问可以可靠处理它的黑匣子,不要试图过度思考它:youtube.com/watch?v=-5wpm-gesOY

标签: c# byte bitarray


【解决方案1】:

因为我们计算的是 right 的位和 left 的项目;例如

 BitArray myBitArray = new BitArray(new byte[] { 10 });

我们为byte10(从算起):

 10 = 00001010 (binary)
            ^
            second bit (which is 1)

当我们从left开始计数对应数组的项时:

 {false, true, false, true, false, false, false, false}
           ^
           corresponding second BitArray item (which is true)

这就是为什么如果我们想要返回一个 byte 数组,我们必须对每个 byte 表示 Reverse,例如Linq 解决方案

  using System.Collections;
  using System.Linq;

  ...

  BitArray myBitArray = ...

  byte[] myByte = myBitArray
    .OfType<bool>()
    .Select((value, index) => new { // into chunks of size 8
       value,
       chunk = index / 8 })
    .GroupBy(item => item.chunk, item => item.value)
    .Select(chunk => chunk // Each byte representation
      .Reverse()           // should be reversed   
      .Aggregate(0, (s, bit) => (s << 1) | (bit ? 1 : 0)))
    .Select(item => (byte) item)
    .ToArray();

【讨论】:

    猜你喜欢
    • 2011-02-02
    • 2010-09-26
    • 2010-10-17
    • 2018-07-16
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多