Search code examples
c++functionif-statementbitwise-operatorsbit-shift

Can someone explain why these two things mean the same thing?


Here are two functions that do the same thing. Can someone explain how?

 void calculateFace(){
   //READ THE DIP SWITCH
   int sw_one = digitalRead(LandingStartSW);
   int sw_two = digitalRead(LandingApproachSW);
   int sw_three = digitalRead(LandingTerminalSW);
 
   displayBitmap = (sw_three << 2) | (sw_two << 1) | sw_one;
 
 }

and

void calculateFace(){
 READ THE DIP SWITCH
 int  sw_one = digitalRead(LandingStartSW);
 int  sw_two = digitalRead(LandingApproachSW);
 int  sw_three = digitalRead(LandingTerminalSW);
 
 if(sw_one == 1 && sw_two == 0 && sw_three == 0) {
 displayBitmap = 1;
}
else if(sw_one == 0 && sw_two == 1 && sw_three == 0) {
 displayBitmap = 2;
}
 else if(sw_one == 1 && sw_two == 1 && sw_three == 0) {
 displayBitmap = 3;
}
else if(sw_one == 0 && sw_two == 0 && sw_three == 1) {
 displayBitmap = 4;
}
else if(sw_one == 1 && sw_two == 0 && sw_three == 1) {
 displayBitmap = 5;
}
else if(sw_one == 0 && sw_two == 1 && sw_three == 1) {
 displayBitmap = 6;
}
else if(sw_one == 1 && sw_two == 1 && sw_three == 1) {
 displayBitmap = 7;
}
else {
 displayBitmap = 0;
}

I tried understanding it myself. I understand that the first one is bitshifting the values, but I can't figure out how that's translating to if else statements.


Solution

  • You can consider the variables sw_one, sw_two, and sw_three as "bits" of one 3-bit number consisting of them. The less significant bit is sw_one, the most significant bit is sw_three, and between them is sw_two.

    This number can contain the following values in binary:

    sw_three sw_two sw_one decimal
    0 0 0 0
    0 0 1 1
    0 1 0 2
    0 1 1 3
    1 0 0 4
    1 0 1 5
    1 1 0 6
    1 1 1 7

    The right hand expression in this statement:

    displayBitmap = (sw_three << 2) | (sw_two << 1) | sw_one;
    

    builds a single 3-bit number as shown above from these three "bit" values.

    The if statements, like for example this:

    else if(sw_one == 1 && sw_two == 0 && sw_three == 1) {
      displayBitmap = 5;
    }
    

    just tests each bit value of a built number and provides the corresponding decimal value.

    Compare this if statement with the binary representation of the value 5 in the above table:

    sw_three sw_two sw_one decimal
    1 0 1 5