将字节数组转换为位数组问题
Posted
技术标签:
【中文标题】将字节数组转换为位数组问题【英文标题】: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]
(与我输入的不完全一样,它只是true
和false
的数组)。在d
中,它被转换为位[0]...位[7],从最不重要的位到最重要的位。这不是我想要的。
我想保存从最高到最低的位:[0110 0001, 0110, 0010, ..., 0110 1010]
。
我该如何处理?
【问题讨论】:
***.com/questions/3587826/… 【参考方案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;
【讨论】:
以上是关于将字节数组转换为位数组问题的主要内容,如果未能解决你的问题,请参考以下文章