将BitSet转换为Byte [] [英] Converting BitSet to Byte[]
问题描述
我有一个BitSet,需要将其转换为Byte [].但是,通过使用BitSet.toByteArray(),我没有得到正确的输出.我已尝试将Byte []转换为其二进制形式,以检查Bitset和Byte []的二进制形式是否相似.
I have a BitSet, which needs to be converted to a Byte[]. However, by using BitSet.toByteArray(), I don't get the correct output. I have tried converting the Byte[] to its binary form in order to check whether the Bitset and the binary form of the Byte[] are similiar.
public static void generate() {
BitSet temp1 = new BitSet(64);
for (int i = 0; i < 64; i++) {
if(i % 8 != 0 && i < 23) {
temp1.set(i, true);
}
}
StringBuilder s = new StringBuilder();
for (int i = 0; i < 64; i++) {
s.append(temp1.get(i) == true ? 1 : 0);
}
System.out.println(s);
byte[] tempByteKey1 = temp1.toByteArray();
for (byte b : tempByteKey1) {
System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
}
}
输出:
Bitset: 0111111101111111011111100000000000000000000000000000000000000000
Converted Byte: 1111111011111110011111100000000000000000000000000000000000000000
它们都是64位,但是BitSet中的第一个0放置在转换后的其他位置.为什么会发生这种情况,我该如何解决?
They are both 64 bits, but the first 0 in the BitSet is placed somewhere else after the conversion. Why is this happening, and how can I fix it?
推荐答案
来自 BitSet#toByteArray()javadoc :
返回一个新的字节数组,其中包含该位集中的所有位.更准确地说,如果..
Returns a new byte array containing all the bits in this bit set. More precisely, if..
byte[] bytes = s.toByteArray();
然后
bytes.length == (s.length()+7)/8
和
s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)
对于所有
n<8 * bytes.length
.
@返回一个字节数组,其中包含该位集中所有位的小端序表示法
@return a byte array containing a little-endian representation of all the bits in this bit set
@自1.7起
注意: toByteArray()
甚至没有声称知道 size()
,对于length()
!
Attention: toByteArray()
doesn't even claim to know size()
, it is only "reliable" regarding length()
!
..因此,我建议采用类似以下的方法作为实现(您的 toBinaryString()
的替代方法):
..So I would propose as implementation (alternative for your toBinaryString()
) a method like:
static String toBinaryString(byte[] barr, int size) {
StringBuilder sb = new StringBuilder();
int i = 0;
for (; i < 8 * barr.length; i++) {
sb.append(((barr[i / 8] & (1 << (i % 8))) != 0) ? '1' : '0');
}
for (; i < size; i++) {
sb.append('0');
}
return sb.toString();
}
..这样称呼:
System.out.println(toBinaryString(bitSet.toByteArray(), 64);
run:
0111111101111111011111100000000000000000000000000000000000000000
0111111101111111011111100000000000000000000000000000000000000000
BUILD SUCCESSFUL (total time: 0 seconds)
这篇关于将BitSet转换为Byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!