Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise Operators java

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!

like image 589
user1057761 Avatar asked Feb 03 '26 12:02

user1057761


2 Answers

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);
like image 69
Mysticial Avatar answered Feb 06 '26 11:02

Mysticial


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.

  • Use equivalent decimal value.

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;
  • Use wrapper classes parse method

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);
  • If you are using Java 7, use binary literals

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;
like image 27
Jomoos Avatar answered Feb 06 '26 11:02

Jomoos