Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Bitwise "&" on integers

I have the following:

 int a = 10001000;
 int b = 10000000;

I want the following output:

 (a&b) = 10000000;

But my problem is that java converts to binary before using the "&" operation, and I'd really like to be able to use this on integers in the above fashion. Can this be done?

like image 871
Fancypants753 Avatar asked Mar 06 '23 11:03

Fancypants753


1 Answers

First, you will need to write the a and b literals with 0b to indicate they are binary. Second, you will need to use something like Integer.toBinaryString(int) to get the binary result of your bitwise &. Like,

int a = 0b10001000, b = 0b10000000;
System.out.printf("(a&b) = %s;%n", Integer.toBinaryString(a & b));

Outputs (as requested)

(a&b) = 10000000;
like image 165
Elliott Frisch Avatar answered Mar 19 '23 14:03

Elliott Frisch