简体   繁体   English

字节到BitSet的转换

[英]Byte to BitSet conversion

I'm using the following code to do the conversion: 我正在使用以下代码进行转换:

public static BitSet fromByte(byte b){
    BitSet bs = new BitSet(8);
    for (int i=0; i<8; i++){  
        if ((b & (1 << i)) > 0){  
            bs.set(i);              
        }  
    } 
    int length = bs.length();

    return bs;
}  

The output is {0, 3, 4, 5, 6}(from debugger display of the bs) - the indexes where the bits are set. 输出为{0,3,4,5,6}(来自bs的调试器显示)-设置位的索引。 I think this should represent 1001111 with length = 7, but is wrong since 1001111 is 79, not 121. Also I want the length to be 8. Basically I want a bitSet with length 8 which represents correctly any byte number. 我认为这应该代表长度为7的1001111,但由于1001111为79,而不是121,所以是错误的。我也希望长度为8。基本上,我想要一个长度为8的bitSet,它可以正确表示任何字节数。 My expectation would be 01111001 and the display of the debugger to show {1,2,3,4,5,7} 我的期望是01111001,调试器的显示将显示{1,2,3,4,5,7}

Bits in a byte are numbered right-to-left, not left-to-right. 字节中的位从右到左编号,而不是从左到右编号。 That's why setting bits {0, 3, 4, 5, 6} defines this pattern: 这就是设置位{0, 3, 4, 5, 6}定义此模式的原因:

7 6 5 4 3 2 1 0
0 1 1 1 1 0 0 1

You are checking the bits in this order: 您正在按以下顺序检查位:

00000001 = index 0
00000010 = index 1
00000100 = index 2
00001000 = index 3
etc.

ie from right to left, and storing them from left-to-right in the bit set. 即从右到左,并将它们从左到右存储在位集中。

{0, 3, 4, 5, 6} is equal to : (2 ^ 0) | {0,3,4,5,6}等于: (2 ^ 0)| (2 ^ 3) | (2 ^ 3)| (2 ^ 4) | (2 ^ 4)| (2 ^ 5) | (2 ^ 5)| (2 ^ 6) (2 ^ 6)

2^0 = 00000001
2^3 = 00001000
2^4 = 00010000
2^5 = 00100000
2^6 = 01000000
--------------
      01111001

Like you guessed, 0 is also the indice of a bit equals to 1. But the bits are ordered from right to left. 就像您猜到的一样,0也是1等于1的指数。但是这些位是从右到左排序的。

The length of the bitset will be as few as bits as necessary to represent the bits you have set. 位集的长度将与表示您已设置的位所需的位一样少。 For instance if you set the first three bits, the length will be 2, as only 2 bits are necessary for representation. 例如,如果您设置前三位,则长度将为2,因为表示仅需要2位。

The constructor of the BitSet sets its Size , not its length . BitSet的构造函数设置其Size ,而不是其length I suspect they are 2 different concepts. 我怀疑它们是两个不同的概念。

When I run your code, I get the result I expect. 当我运行您的代码时,我得到了我期望的结果。 Are you sure of the value you are passing in? 您确定所传递的价值吗? Perhaps you are confused about the endianess of your bits? 也许您对位的持久性感到困惑? Usually its read from right to left, not left to right (or big endian bitwise order ) 通常从右向左读取,而不是从左向右读取(或大尾数位按位顺序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM