MrGibbage
MrGibbage

Reputation: 2646

Java bit shifting... please explain

I am reviewing some code from an alarm clock project. The code uses an integer to store recurring alarm information. That is, an alarm that occurs say, every MWF. I understand that integers are simply a series of bytes, and each byte is a series of bits, so you can use that bit information to create an integer that will be unique for every pattern of days of the week. What I don't understand is the logic in these functions:

// is a given day "set"?
private boolean isSet(int day) {
  return (mDays & (1 << day)) > 0;
}

// set a given day to on or off
public void set(int day, boolean set) {
    if (set) {
        mDays |= (1 << day);
    } else {
        mDays &= ~(1 << day);
    }
}

Could someone please explain what these two function do and how they work?

Upvotes: 2

Views: 127

Answers (1)

Mike Christensen
Mike Christensen

Reputation: 91608

The isSet Function:

Basically the expression:

(1 << day)

Means take the number 1:

00000001

And shift it over day number of positions to the left. Such as if day were 3, you'd have:

00001000

You can use the bitwise & operator to check for common bits. Such as:

00001000
&
00001000

Will equal

00001000

However,

00001000
&
00000001

Will equal 0. Using this, you can check if that particular bit was set, since if you & the number with the bit you're looking for, you're guaranteed to get a number over 0 if that bit matches.

The set Function:

The expression:

mDays |= (1 << day);

Is equivalent to:

mDays = mDays | (1 << day);

This will basically force the bit expressed with (1 << day) to be true. Say we wanted to flip the 1st bit on:

00001000 | 00000001
Equals:
00001001

The expression:

mDays &= ~(1 << day);

Will basically do the inverse of that. The ~ operator inverts the bits (every 1 becomes a 0, every 0 becomes a 1). This will ensure that the bit you're setting becomes 0, since anything & 0 is 0. The existing on bits will stay, since the other bits in ~(1 << day) are all 1.

Upvotes: 6

Related Questions