Getting the position of a given bit in an integer

I use the following trick to iterate through a set of int bits:

while (b != 0) { c = b & (0 - b); //Do something... b = b ^ c; } 

As an example, the number 4128 (binary 0001000000100000) works fine because the values ​​of c are 32 and 4096.

However, instead of the actual values, I need the positions of these values, these are 5 and 12.

Is there an extra line of code that can be inserted into a loop that will return a position?

+4
source share
5 answers

You can use Integer.numberOfTrailingZeros to get the bit index, for example:

 while (b != 0) { c = b & (0 - b); int index = Integer.numberOfTrailingZeros(c); //Do something... b = b ^ c; } 
+3
source

Ineffective answer, but in honor of the trick you use. I changed it to b &= (b - 1) .

 int bitCount(int b) { int bits = 0; while (b != 0) { int nextb = b & (b - 1); // Remove the rightmost bit 1 int power2ofBitIx = b ^ nextb; // Get the lost bit 10..0 int bitIx = bitCount(power2ofBitIx - 1); // And count 1..1 // Do something with bitIx b = nextb; ++bits; } return bits; } 
+1
source

Read Jerry Coffin's answer .

You can get the positions of the given int bits using a mask, and AND-each each bit:

 int c = 4128; int two_32 = pow(2, 32); for (int mask = 1, iter = 1; mask < two_32; mask <<= 1, iter++) if (c & mask) printf("Flag: %d set\n", iter); 

This should print:

 Flag: 0 set Flag: 5 set 
0
source

If you are going to make a beeborn game, you will not need bit positions, but values.

I have never seen your while loop, good. Personally, I like this one:

 int tst = 255; for(int looper = tst, i = Integer.highestOneBit(looper); looper != 0; looper &= ~i, i = Integer.highestOneBit(looper)) { System.out.println(i); } 
0
source

public boolean isBitSet (int position) {

  int value = Integer.parseInt("0000000000000000000000000000000", 2); BigInteger b = new BigInteger(String.valueOf(value)); b = b.setBit(4); return b.testBit(4); 

}

0
source

Source: https://habr.com/ru/post/1469468/


All Articles