Dooggy
Dooggy

Reputation: 11

Bitwise AND operator(&) doesn't works as I expected it to work

I brought the characteristic property which is 10 into int variable charaProp.

final int charaProp = characteristic.getProperties();

And I brought the filtering property which is 2(BluetoothGattCharacteristic.PROPERTY_READ) into int variable property.

final int property = BluetoothGattCharacteristic.PROPERTY_READ;

I bitwise ANDed charaProp and property to see which one, read or write, to perform.

final int tmp = charaProp & property;

Too weird, the AND operator of which the result should be 0, produces 2. Screen shot

And flow goes to perform read action.

 if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
             mBluetoothLeService.readCharacteristic(characteristic);
 }

I really don't know why this happens?

Please help me. Thanks in advance!!!

Upvotes: 1

Views: 481

Answers (3)

xenteros
xenteros

Reputation: 15842

It's nothing strange about it:

     DEC  BIN
   a  10: 1010
   b   2: 0010
  a&b  2: 0010

The bitwise operator & takes the binary representation of two numbers and performs bit-and on those bits.

a&b will result in 0 in case:

  • a==0 || b == 0
  • a, b differ on each but where one of them has a bit set.

HINT:
I have a very important hint for you. Do NOT assume that Java is not working in a way it should. It's probably an issue in your code logic. Your title should be: Java operator & not working as I expected it to work. In the end, Java always works according to the specification. The problems are always with logic. Sometimes obvious, sometimes logic and knowledge about how the computers (and JVM) work.

Upvotes: 1

Travis Well
Travis Well

Reputation: 965

This is correct behavior. Look at the binary representations of these numbers.

10 == 0b1010

That's 8 (0b1000) + 2 (0b10). So 10 & 2 == 2. Try it out:

assert 0b1010 & 0b0010 == 2;

The & operator lines up the bits and does a logical and for each pair. Clearly, the second least significant bit in both 10 and 2 is 1. So if we think of the second bit as a boolean, true && true == true.

Upvotes: 0

Zarwan
Zarwan

Reputation: 5777

10 in binary is 1010. 2 in binary is 10. 10 & 1010 = 10 = 2 in base 10.

Upvotes: 0

Related Questions