emilly - 1 year ago 76
Java Question

# How to convert binary input into expected result?

I have three characters say a,b,c . Here is the binary representation of a, b, c

``````a 001
b 010
c 100
``````

what I want is when someone provide input as
`011`
, output should be
`a,b`

Here is expected output

``````input   output
001     a
010     b
011     b,a
100     c
101     c,a
110     c,b
111     c,b,a
``````

What is the efficient way to achieve this? I vaguely recalls there was some binary operator to achieve the same but i could not recollect this.

You could use the `&` (bitwise and) operator and check if the result is not 0 to see if the integer is composed of a certain binary number.

`(011 & 001) != 0`

`(010 & 001) == 0`

`(010 & 010) != 0`

``````final int a = 0b001, b = 0b010, c = 0b100;
int val = 0b011;
boolean containsA = (val & a) != 0; // true
boolean containsC = (val & c) != 0; // false
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download