Oli Black
Oli Black

Reputation: 441

Checking a single bit using the bitwise and (ampersand) operator

I am trying to understand this bit of code, the method addBittoTree needs a boolean to be passed through. I am not quite sure as to what it is checking. I do not understand why there is an ampersand for currentByte and -128, is it using that as an addition operator?

byte currentByte = dis.readByte();
tree.addBitToTree( (currentByte & -128) == -128 );

Upvotes: 1

Views: 1391

Answers (1)

jlordo
jlordo

Reputation: 37813

-128 in two's complemenet is

1000 0000

let's say your currentByte has the first bit set:

    1000 0000 // -128
        &     // bitwise logical and
    1010 1010 // currentByte (example)
is
    1000 0000 // -128

That is compared (==) to -128, so you are passing the boolean parameter true.

Another example where the first bit is not set:

    1000 0000 // -128
        &     // bitwise logical and
    0011 1110 // currentByte (example)
is
    0000 0000 // 0

That is compared (==) to -128, so you are passing the boolean parameter false.

Since this way of doing it always passes true to the method, when the first bit is set, and false, when it is not set, and we know that all positive numbers don't have the first bit set and all the negative ones do, it is equivalent to simply write:

tree.addBitToTree(currentByte < 0);

Upvotes: 5

Related Questions