Search code examples
javabitwise-operatorsbitwise-and

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?


Solution

  • 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;