Get the least significant bit of an integer in Java

4

I'm trying to do a bit manipulation in java, but I'm having a problem.

I'm storing any number in an int and trying to get the least significant bit of it, but I do not know how to do that.

For example:

int valor = 98;

The value in binary 98 is 1100010 and I'm trying to get and save in another int only 0 (110001'0 '), and do this with any number independent of size.

Could you help me?

    
asked by anonymous 11.07.2018 / 01:49

1 answer

8

In order to get the least significant bit, just do the bitwise% operation of the integer you want to get the bit with the number 1. In binary (32 bits) the 1 is represented by the first 31 bits 0 and the bit less significant 1, with the AND, all other bits will be zeroed.

The code would be:

int least_significant = valor & 1;
    
11.07.2018 / 02:40