Get the least significant bit of an integer in Java

Asked

Viewed 101 times

4

I’m trying to do a bit manipulation in java, but I have a certain problem.

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

For example:

int valor = 98;

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

Could you help me?

  • Size independent? So I can have a housing structure imposed by me, other than the primitive Java standard types?

1 answer

8


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

The code would be:

int least_significant = valor & 1;
  • Thank you so much for helping Begnini.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.