Extract last 2 bits in binary format

I am java noob, so please bear with me if I do not explain my problem very well.

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

+4
source share
3 answers

Suppose you want to get the numerical value of the last two 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 does is take a number, in this case, 0b1110and do it andwith the mask installed 0b11.

0b , java, .

, : Integer.toBinaryString(n & mask)

+4

% , , Integer.toBinaryString(), charAt(), 2 , ?

+3

, x % 4 x & 3.

x % 4 - 4, 0 - 3, .

x & 3 - 11, .. .

The second, usually the fastest at runtime and preferred method for processing bits. (Use the bit-wise operator to manipulate the bits, right?)

0
source

All Articles