Reputation: 3
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
Upvotes: 0
Views: 91
Reputation: 3017
You can directly do bitwise operators on int values (Java will do the binary conversion)
public static void main(String[] args) throws ParseException {
int demo = 127;
System.out.println(demo);
System.out.println("demo is: " + (demo & 3));
}
Reference:http://www.tutorialspoint.com/java/java_bitwise_operators_examples.htm https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
or you can convert your octal value to binary representation as:
00000011
to
0b00000011
Which is already pointed in above answer
Upvotes: 0
Reputation:
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));
Upvotes: 3