'extract the last 2 bits in binary

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?



Solution 1:[1]

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)

Solution 2:[2]

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?

Solution 3:[3]

The last two bits can be obtained by doing x % 4, or by doing x & 3.

x % 4 is remainder after division by 4, which is a number 0-3, as represented by the last two bits.

x & 3 is a bit-wise AND operation with the binary number 11, i.e. zero'ing all other bits.

The second is generally the fastest at runtime, and the preferred method for doing bit manipulation. (Use a bit-wise operator for bit manipulation, right?)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nooblhu
Solution 3 Andreas