user3508197 - 2 months ago 24

Java Question

I am trying to find some code that will easily break now a binary string. I'm not even sure I'm asking this question correctly, but I want to get the value of each "active bit". For example, if I have a binary string of 100000001, I would like to return the values 256, 1 in an array. I'm trying to figure this out so I can use a lookup table in SQL which has an integer column and a text column. The integer column will be used to determine which text values will be written to a new table. So, the value "Text1" at 1, and "Text 2" at 256 would both be written to the new table, but the number submitted to get those values would be 257.

I know I'm rambling, but I would input a value, 257, and I convert it to a binary string of 100000001. Now I want some code to break that binary string into two values... 1 and 256. Am I making any sense?

Answer

You don't need to convert to a binary string if you use `Integer.highestOneBit`

. You can loop through the one bits, filling in an array of size `Integer.bitCount`

with each call to `Integer.highestOneBit`

. Afterwards, you can xor with the value of the highest bit to remove it from the number.

```
public static int[] getOneBits(int num) {
int[] oneBits = new int[Integer.bitCount(num)];
for (int i = 0; i < oneBits.length; i++) {
oneBits[i] = Integer.highestOneBit(num);
num ^= oneBits[i];
}
return oneBits;
}
```

This will produce an array, where all of the values are powers of 2 in descending order, where the sum of all the elements will be the original number. For example, `257`

will produce `[256, 1]`

, and `127`

will produce `[64, 32, 16, 8, 4, 2, 1]`

.