M GARCIA M GARCIA - 27 days ago 13
Java Question

Binary numbers in Java Least Significant

Im trying to write a method that returns me the least 2 significant binary numbers of any number from 0 to 255 both inclusive, which returns it in decimal, apparently I could use mod operator % but I dont know what to do because with this method it doesnt return me the correct 2 least sig. For 19, it should return 3 since the last 2 significant (11) are equal to 3 in decimal

public static int getLeastSignificant2( int num )

{

int first = num<<6

int finalD = first>>>6;

return finalD;
}

Answer

you should be able to bitwise and the number by 3 (11 in binary). This would zero out all the other bits except the 2 least significant bits.

public static int getLeastSignificant2(int num) {
    // return num & 3; // if you don't want to use a binary literal
    return num & 0b11;
}

with this I get System.out.println(getLeastSignificant2(19)); //=> 3

if you wanted to use the mod operator could do this. I think the compiler ends up converting this to use a bitwise and under the hood.

public static int getLeastSignificant2(int num) {
    return num % 4;
}