my code is
final int CONST_1 = 1010;
final int CONST_2 = 1011;
System.out.println("CONST_1 & CONST_2: " + Integer.toBinaryString(CONST_1 & CONST_2));
System.out.println("CONST_1 ^ CONST_2: " + Integer.toBinaryString(CONST_1 ^ CONST_2));
System.out.println("CONST_1 | CONST_2: " + Integer.toBinaryString(CONST_1 | CONST_2));
System.out.println("~CONST_1 : " + Integer.toBinaryString(~CONST_1));
Output is
CONST_1 & CONST_2: 1111110010
CONST_1 ^ CONST_2: 1
CONST_1 | CONST_2: 1111110011
~CONST_1 : 11111111111111111111110000001101
In my opinion it's wrong and it should be:
CONST_1 & CONST_2: 1010
CONST_1 ^ CONST_2: 1
CONST_1 | CONST_2: 1011
~CONST_1 : 101
Please explain me why I have such result. Thanks!
Change this:
final int CONST_1 = 1010;
final int CONST_2 = 1011;
to this:
final int CONST_1 = 0b1010;
final int CONST_2 = 0b1011;
Don't forget that literals are decimal by default. You clearly wanted them to be binary.
Binary literals require Java 1.7. So if that's not available, you can go with this:
final int CONST_1 = Integer.parseInt("1010",2);
final int CONST_2 = Integer.parseInt("1011",2);
I think you know what is meant by a literal. If not, please refer: Java Literals and Literal.
Now, Integer and Floating-Point literals are decimal by default in Java. So, the value 1010 you typed above will be decimal 1010. ie., One thousand and ten. If you want them to be binary (it is clear from the question), there are many possibilities.
You may use the decimal equivalent of the binary value you want to represent. Here, for example, decimal equivalent of binary 1010 is 10, and that of binary 1011 is 11.
final int CONST_1 = 10;
final int CONST_2 = 11;
Each wrapper class has a parse method, which takes the base of number system also as argument. So
final int CONST_1 = Integer.parseInt("1010", 2);
final int CONST_2 = Integer.parseInt("1011", 2);
Binary literals are not supported in older versions of Java. Java 7 introduces binary literals. See features.
final int CONST_1 = 0b1010;
final int CONST_2 = 0b1011;
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