0

I'm working on a project in java recently and i would like to handle the bits of an integer so that i can check the i lsb of a number. I have found a lot of approaches but nothing that can handle properly...

Example

key= 4 Key 4 in binary is 100 I would like in some way to extract the 3rd LSB of 4 which is 1. Is there an algorithm that can do that?

Antifa
  • 377
  • 1
  • 4
  • 14

3 Answers3

4

Using bit-shifting and bitwise AND: (indexed from 0)

int getBit(int number, int index)
{
  return (number >> index) & 1;
}

getBit(4, 2) returns 1.

You can also use % 2 instead of & 1.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
2

Make a bitmask and shift:

int bitmask = 4;

int extractedBit = (i & BIT3) >> 2; // is now the 3rd lsb.
trutheality
  • 23,114
  • 6
  • 54
  • 68
1

Okay, try this. Since the 3rd LSB would be based on the value of the units place of the number no mater however large it be, the value would be 0 if it was either less than four or greater than 7. So (0,1,2,3)U(8,9) in the units place give 3rd LSB as 0. (4,5,6,7) give 1.

int key = 12000;
int i=4;
if((key/(10^(i-1))%10 < 4 || (key/(10^(i-1))%10 >7)
    lsb3 = 0;
else
    lsb3 = 1;
hanut
  • 505
  • 4
  • 24