0

In Java, having a number like 0b1010, I would like to get a list of numbers "composing" this one: 0b1000 and 0b0010 in this example: one number for each bit set.

I'm not sure about the best solution to get it. Do you have any clue ?

1
  • use bitwise operators to check if it is set in the value you want Commented Mar 31, 2016 at 15:10

3 Answers 3

1

Use a 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);
}

Output:

1
2
8
32

If you really want them printed out as binary strings, here's a little hack on the above method:

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';
}

Output:

000001
000010
001000
100000
Sign up to request clarification or add additional context in comments.

2 Comments

You can use Integer.toBinaryString() :)
D'oh! You know, I knew there had to be some method for that - looked all over java.text and java.util.Formatter and gave up. Whoops!
1

Scan through the bits one by one using an AND operation. This will tell you if a bit at one position is set or not. (https://en.wikipedia.org/wiki/Bitwise_operation#AND). Once you have determined that some ith-Bit is set, make up a string and print it. PSEUDOCODE:

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);
        }
   }
}

Comments

0

Here is a little test that works for me

 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;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.