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?
-
2How do you want to "grab" them? You want to obtain a `String` "10" or a number "2"? – Federico Nafria May 16 '16 at 22:50
-
I need to write the method so that the following in main will be correct: result = getLeastSignificant2(255); System.out.println( "The result of getLeastSignificant2(255) is " + result ); if ( result == 3 ) { System.out.println( "This is correct!" ); }else { System.out.println( "This is WRONG! Should be 3" ); } – dye May 16 '16 at 23:20
3 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)

- 1,397
- 14
- 39
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?

- 552
- 15
- 33
-
Can you help me? Why when I mask the negating bit and shift it I get a negative value. eg: 10000000 | 00000000 | 00000000 | 00000000. Here I have an int with the negating bit on. If I shift it to the right. { 00000000 | 00000000 | 00000000 | 00000001 } and mask that one bit I get -1. In.Cpp I would get 1. – Feb 06 '20 at 19:22
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?)

- 154,647
- 11
- 152
- 247
-
x & 3 only works for 255, but what if I wanted to get the last 2 bits of 64? – dye May 17 '16 at 00:08
-
@dye `64 & 3 == 0`. `64` (decimal) is `01000000` (binary), and the last 2 bits are `00`. Which part confused you? – Andreas May 17 '16 at 00:37