0

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

2
  • 1
    00000011 is an octal literal, value 8+1 = 9. Commented May 17, 2016 at 9:44
  • Thank you Patricia, it works now. I have noticed that if I add the number as a byte (for example, 3 instead of 00000011) it works too. Commented May 17, 2016 at 10:02

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your answers! It works fine now. I have noticed that if I add the number as a byte (for example, 3 instead of 00000011) it works too.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.