获取组成数字的二进制数列表

时间:2016-03-31 14:58:06

标签: java

在Java中,有一个像0b1000这样的数字,我想得到一个数字列表"撰写"这一个:在此示例中为0b0010cp:每个位集都有一个数字。

我不确定获得它的最佳解决方案。你有什么线索吗?

3 个答案:

答案 0 :(得分:1)

使用AND操作逐个扫描这些位。这将告诉您是否设置了一个位置的位。 (https://en.wikipedia.org/wiki/Bitwise_operation#AND)。一旦确定设置了某个ith-Bit,就组成一个字符串并打印出来。伪代码:

public static void PrintAllSubbitstrings(int number)
{
   for(int i=0; i < 32; i++) //32 bits maximum for an int
   {
        if( number & (1 << i) != 0) //the i'th bit is set.
        {
            //Make up a bitstring with (i-1) zeroes to the right, then one 1 on the left
            String bitString = "1";
            for(int j=0; j < (i-1); j++) bitString += "0";
            System.out.println(bitString);
        }
   }
}

答案 1 :(得分:1)

使用BitSet

long x = 0b101011;
BitSet bs = BitSet.valueOf(new long[]{x});
for (int i = bs.nextSetBit(0); i >=0 ; i = bs.nextSetBit(i+1)) {
    System.out.println(1 << i);
}

输出:

1
2
8
32

如果你真的希望它们打印成二进制字符串,那么上面的方法有点破解:

long x = 0b101011;
char[] cs = new char[bs.length()];
Arrays.fill(cs, '0');

BitSet bs = BitSet.valueOf(new long[]{x});
for (int i = bs.nextSetBit(0); i >=0 ; i = bs.nextSetBit(i+1)) {
    cs[bs.length()-i-1] = '1';
    System.out.println(new String(cs));  // or whatever you want to do with this String
    cs[bs.length()-i-1] = '0';
}

输出:

000001
000010
001000
100000

答案 2 :(得分:0)

这是一个适合我的小测试

 public static void main(String[] args) {
   int num = 0b1010;
   int testNum = 0b1;
   while(testNum < num) {
       if((testNum & num) >0) {
           System.out.println(testNum + " Passes");
       } 
       testNum *= 2;
   }
}