Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract the last 2 bits in binary

Tags:

java

binary

bit

The number 254 is 11111110 in binary. My problem is I want to grab the last 2 bits (10). I was told to use the % operator to do this but I don't know how. Can anyone help me with this problem?

like image 365
dye Avatar asked Feb 08 '23 00:02

dye


2 Answers

Supposing you want to get the numeric value of the last 2 binary digits, we can use a mask.

public static void main(String[] args) {
    int n = 0b1110;
    int mask = 0b11;
    System.out.println(n & mask);
}

What the code is doing is taking the number, in this case 0b1110 and doing an and with the mask defined 0b11.

0b is how you tell java that you are expressing the number as binary.

In case you wanted to obtain the binary number as binary, you can use this: Integer.toBinaryString(n & mask)

like image 66
Federico Nafria Avatar answered Feb 20 '23 00:02

Federico Nafria


You can use % to convert to binary but I believe its easier to use Integer.toBinaryString() and then charAt() to get the last 2 characters like they do in here How do you get the last character of a string?

like image 44
Nooblhu Avatar answered Feb 20 '23 00:02

Nooblhu