4

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?

Fancypants753
  • 429
  • 1
  • 6
  • 19
  • 1
    "bitwise and", as the name suggests, works on bits. You can't make it work on decimal digits. Imagine you would use it to compute the `&` of digit 4 and digit 3. What should the result be? – Henry Apr 07 '18 at 06:22

1 Answers1

7

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;
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • ok, is it possible to turn a string "0b10001000" back into the binary int representation? Also, thanks for answering. – Fancypants753 Apr 07 '18 at 06:36
  • @Fancypants753 `int` is a 32-bit binary type. What are you asking? How to say `int c = 136;`? *Or*, `System.out.println(Integer.parseInt("0b10001000".substring(2), 2));` – Elliott Frisch Apr 07 '18 at 06:38
  • I want something like Integer.parseInt("0b10001000"); to return int 0b10001000 – Fancypants753 Apr 07 '18 at 06:41