bitwise AND in java with operator "&"
Asked Answered
R

4

5

I just read this code following:

byte[] bts = {8, 0, 0, 0};
if ((bts[i] & 0x01) == 0x01)

Does this do the same thing as

if (bts[i] == 0x01)

If not,what's the difference between them?

And what is the first way trying to do here?

Rockery answered 31/7, 2013 at 10:54 Comment(0)
S
13

No, it doesn't.

if(bts[i] == 0x01)

means if bts[i] is equal to 1.

if((bts[i] & 0x01) == 0x01) 

means if the least significant bit of bts[i] is equal to 1.

Example.

bts[i] = 9 //1001 in binary

if(bts[i] == 0x01) //false

if((bts[i] & 0x01) == 0x01) //true
Snocat answered 31/7, 2013 at 10:56 Comment(3)
@Johnny: E.g., all odd numbers match the & 0x01 test, but only 0x01 matches the == 0x01 test.Wenger
It seems that all odd numbers will return true here.Rockery
@JohnnyChen: Do I hear an echo? ;-)Wenger
S
2

(0x1001 & 0x01) == 0x01, but

0x1001 != 0x01
Suburban answered 31/7, 2013 at 10:56 Comment(0)
B
2

No, it doesn't, the first will check only the last bit - if it's 1, it will return true regardless of the others.

The second one will return true if only the last bit is 1.

Bowden answered 31/7, 2013 at 10:56 Comment(0)
C
1

No, it's not the same thing. 0x01 is just 1. Now,

if (bts[i] == 0x01)

checks if bts[i] is equal to 1.

if ((bts[i] & 0x01) == 0x01)

Checks if the last (least significant) bit of bts[i] is equal to 1. In the binary system, all odd numbers have the last bit equal to 1. So, if ((bts[i] & 0x01) == 0x01) is basically checking, if the number in bts[i] is odd. It could be written as if (bts[i] % 2 == 1), too.

Colley answered 31/7, 2013 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.