JavaLearner
JavaLearner

Reputation: 17

What exactly is the last piece of code doing?

protected boolean[] bitArray = new boolean[8];

protected void readNextByte() throws IOException {

    latestReadByte = reader.read();
    int decimtalTal = latestReadByte

    for(int n= 0; n < 8; n++){
        int pos = (int)Math.pow(2, n);

        bitArray[7-n] = (decimalTal & pos) == pos;  // THIS LINE

        // what is the bitwise And in bracket == pos supposed to mean?
    }
}

Upvotes: 0

Views: 432

Answers (2)

user949300
user949300

Reputation: 15729

@VGR is correct, but to point out a small subtlety when you run into similar code in the future:

(decimalTal & pos) == pos tests if all the bits in pos are also set in decimalTal

(decimalTal & pos) != 0 test if any of the bits in pos are also set in decimalTal

In this example, pos only has 1 bit set because it is a power of 2 so it doesn't matter.

Upvotes: 0

VGR
VGR

Reputation: 44355

The code on the right-hand side of the bitArray[7-n] = assignment is testing whether bit n of decimalTal is set. It evaluates to true if the bit is set (nonzero), false if the bit is clear (zero).

Upvotes: 2

Related Questions