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?
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)
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With