我怎么能位转换为字节? [英] How can I convert bits to bytes?
问题描述
我有128布尔值的重新present位的数组。我怎样才能将这些128位再presentations为16个字节?
例如:
我有一个数组,看起来像这样:
0110001100110000100010111011001011010011010001010001101101001100
1000010000000000001000111111111101000011111001111011111011111001
(转换为1和0更简洁)
我需要将这些位转换为下面的字节数组:
99 48 139 178 211 69 27 76 132 0 35 255 67 231 190 249
编辑:这似乎没有工作:
字节公众[] ToByteArray(){
INT的numBytes =计数/ 8;如果(_bits.Count%8!= 0)的numBytes ++;字节[]字节=新的字节[的numBytes]INT byteIndex = 0,bitIndex处= 0;的for(int i = 0; I< _bits.Count;我++){
如果(_bits [I])
字节[byteIndex] | =(字节)(1 <<;&下; bitIndex处);++ bitIndex处;
如果(== bitIndex处8){
bitIndex处= 0;
byteIndex ++;
}
}返回字节;
}
它输出:
198 12 209 77 203 162 216 50 33 0 196 255 194 231 125 159
在code治疗是第一位的字的低位,所以你最终扭转的每个单词。作为一个快速和肮脏的修复,试试这个:
字节[byteIndex] | =(字节)(1 LT;≤(7 bitIndex处));
这使第一比特阵列中在第一个字节,等等的最高位置。
I have an array of 128 booleans that represent bits. How can I convert these 128 bit representations into 16 bytes?
Example:
I have an array that looks like this:
0110001100110000100010111011001011010011010001010001101101001100
1000010000000000001000111111111101000011111001111011111011111001
(Converted to 1s and 0s to be more concise)
I need to convert those bits to the following byte array:
99 48 139 178 211 69 27 76 132 0 35 255 67 231 190 249
EDIT: This doesn't seem to work:
public byte[] ToByteArray() {
int numBytes = Count / 8;
if (_bits.Count % 8 != 0) numBytes++;
byte[] bytes = new byte[numBytes];
int byteIndex = 0, bitIndex = 0;
for (int i = 0; i < _bits.Count; i++) {
if (_bits[i])
bytes[byteIndex] |= (byte)(1 << bitIndex);
bitIndex++;
if (bitIndex == 8) {
bitIndex = 0;
byteIndex++;
}
}
return bytes;
}
It outputs:
198 12 209 77 203 162 216 50 33 0 196 255 194 231 125 159
The code is treating the first bit as the low bit of the word, so you end up with each word reversed. As a quick-and-dirty fix, try this:
bytes[byteIndex] |= (byte)(1 << (7-bitIndex));
That puts the first bit in the array at the highest position in the first byte, etc.
这篇关于我怎么能位转换为字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!