Sign in
Log inSign up

Need explanation on Shift & Bitwise operators

Rajkumar's photo
Rajkumar
·Dec 15, 2016

Hi all, Sorry if this sounds so noob, but I never worked in shift or bitwise operators in my code, like ever. But I do understand basic stuff about them.

So recently I had stumbled upon a code, which will get all shift timing from user, and arrange them nicely for displaying. So what I would like to know is, how these particular code blocks work. (Marked with "This Code"). After looking at this, I checked out Calendar class in java, and even they used it in many places. Now I am curious to understand and learn more about this!

int[] hours = new int[7];
    static final String[] namesOfDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
public void addNewShift(final int startTime, final int endTime, int[] days) {
    for (int i = startTime; i <= endTime; i++) {
        This code=> for (int d : days) hours[d] |= (1 << i);
    }
}

    public void displayHours() {
    final StringBuilder sb = new StringBuilder();
    String prevDay = getDayForInt(hours[0]);
    String startDay = namesOfDays[0];
    String endDay = namesOfDays[0];
    for (int i = 1; i < hours.length; i++) {
        final String day = getDayForInt(hours[i]);
        if (day.equals(prevDay)) endDay = namesOfDays[i];
        else {
            appendDayString(sb, startDay, endDay, prevDay);
            prevDay = day;
            startDay = endDay = namesOfDays[i];
        }
    }
    appendDayString(sb, startDay, endDay, prevDay);
    System.out.println(sb.toString());
}

    String getDay(final int shiftVal) {
    final StringBuilder sb = new StringBuilder();
    int startHour = -1, endHour = -1;
    for (int i = 0; i <= 24; i++) {
        This code=> if (((1 << i) & shiftVal) > 0) {
            if (startHour == -1) startHour = i;
            endHour = i;
        } else if (startHour >= 0) {
            sb.append("\t" + hourFormat(startHour) + " to " + hourFormat(endHour) + "\n");
            startHour = endHour = -1;
        }
    }
    if (startHour >= 0) sb.append("\t" + hourFormat(startHour) + " to " + hourFormat(endHour) + "\n");
    return sb.toString();
}

The higlighted part is what's bugging me. It would be of great help if you guys can explain this to me, so I guess I can use them in some other cases!

Gist of the complete code : https://gist.github.com/rajkumarpb/94030e029e351f4562d2344e0d1e5e2c