【问题标题】:Convert byte array to bit array issue将字节数组转换为位数组问题
【发布时间】:2016-02-22 17:39:03
【问题描述】:

我有字符串“abcdefghij”,我想把这个字符串放在位。我试过这样:

byte[] K = new byte[10 * sizeof(char)];
K = System.Text.Encoding.UTF8.GetBytes(args[1]);
var d = new BitArray(k);

K 我有[0x61, 0x62, ..., 0x6a] - 没关系。但是在d 中,我有[1000 0110, 0100 0110, ..., 0101 0110](与我输入的不完全一样,它只是truefalse 的数组)。在d 中,它被转换为位[0]...位[7],从最不重要的位到最重要的位。这不是我想要的。

我想保存从最高到最低的位:[0110 0001, 0110, 0010, ..., 0110 1010]

我该如何处理?

【问题讨论】:

标签: c# arrays bytearray endianness bitarray


【解决方案1】:

我找到了答案。 在我的情况下,我可以使用 this 帖子中的那段代码:

byte[] bytes = ...
bool[] bits = bytes.SelectMany(GetBits).ToArray();

...

IEnumerable<bool> GetBits(byte b)
{
    for(int i = 0; i < 8; i++)
    {
        yield return (b & 0x80) != 0;
        b *= 2;
    }
}

现在在bits 我有我想要的。

这是逆变换:

static byte[] GetBytes(bool[] bits)
{
    byte[] bytes = new byte[bits.Length / 8];
    for (int i = 0; i < bits.Length / 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            bytes[i] |= (byte) (Convert.ToByte(bits[(i * 8) + (7 - j)]) << j);
        }
    }
    return bytes;
}

【讨论】:

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