Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise AND in java with operator "&"

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?

like image 283
Johnny Chen Avatar asked Jul 31 '13 10:07

Johnny Chen


People also ask

What is bitwise AND operator in Java?

A bitwise operator in Java is a symbol/notation that performs a specified operation on standalone bits, taken one at a time. It is used to manipulate individual bits of a binary number and can be used with a variety of integer types – char, int, long, short, byte.

What is && operator in Java?

The symbol && denotes the AND operator. It evaluates two statements/conditions and returns true only when both statements/conditions are true.

What is & In bitwise operator?

The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.

Is it && or & in Java?

The key difference between && and & operators is that && supports short-circuit evaluations while & operator does not. Another difference is that && will evaluate the expression exp1, and immediately return a false value if exp1 is false.


1 Answers

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
like image 101
Armen Tsirunyan Avatar answered Oct 15 '22 18:10

Armen Tsirunyan