Jesus Jesus - 6 months ago 17
Java Question

Issue finding out bits values from byte in Java

I am having an issue trying to find the bit-wise values of a Java byte type. When I try to obtain the value of a certain number of bits by using the bit-wise operator & this value is not the way I foresee it. The (very simple) code is as follows:

public class Demo
{
public static void main(String[]arg)
{
byte demo = 127;
System.out.println("demo is: "+(demo & 00000011));
}
}


In this case, I expect to obtain a 3 (since what I am expecting is 01111111 AND 00000011 = 00000011) but I obtain a 9 (00001001). If I do it with 00000111 then the result is 73 (01001001) rather than 7. Why are there two zeros that are introduced in the comparison?

I have checked the answers that were given to other questions but they are not working in my case, or are not exactly the same thing i am requesting. I am sure there must be some kind of minor thing but I am unable to find how.

Thanks in advance

Answer

As Patricia already pointed out: Java interpretes numbers starteing with leading zeros as being octal values.

If you want the number to be binary, mark it with a leading "0b":

System.out.println("demo is: "+(demo & 0b00000011));
Comments