Mason O'Connor
Mason O'Connor

Reputation: 1

Can someone explain what the following expression does in this program?

String convertByteToBase4(byte x) {
    String result = “";
    for (int i=0; i<4; i++) {
        result = "0123".charAt(x & 3) + result;
        x = (byte)(x>>2)
    }
    return result;
}

Im confused as to what the purpose of the &3 is in this code, is it supposed to add the short for 3 to the byte x?

Upvotes: 0

Views: 70

Answers (3)

Bohemian
Bohemian

Reputation: 425033

& is the bitwise AND operator, but when the bitwise operand is 2n - 1, & is the same as % with the operand plus 1, ie, these two are the same (for positive x):

x & 3 // AND with 11
x % 4 // modulo 4

In your case, & 3 (or % 4) only produces values between 0 and 3 inclusive (for positive x).

Upvotes: 1

ghchoi
ghchoi

Reputation: 5156

"0123".charAt(x & 3)

charAt returns a character of the given string at the given index. In this case, the string is "0123" and the index is determined by x & 3.

3 is 0000 0011 in binary. 2-bit binary number ranges [0, 3]; 00, 01, 10, and 11.

x & 3 masks out higher bits in x:

  x7 x6 x5 x4 x3 x2 x1 x0
&  0  0  0  0  0  0  1  1
-------------------------
                    x1 x0

So you can simply think x & 3 as x % 4. And, definitely, bit-wise operation is much faster than arithmetic operation.

Upvotes: 0

Chris Foley
Chris Foley

Reputation: 454

You are converting to base 4, which means two bits for each digit.

3 is the binary 11, which is two bits.

& 3 is the bitwise and, which effectively isolates the rightmost two bits, or the rightmost base 4 digit.

This is coupled with >>2 which shifts the number two bits to the right.

The whole loop: gets the rightmost two bits, shifts two bits, gets the next two bits, shifts, etc.

Upvotes: 1

Related Questions