Bitwise right shift

From Microduino Wiki
Jump to: navigation, search
  • bitshift left (<<), bitshift right (>>)
  • Description

There are two bitwise shift operators in The Bitmath Tutorial of Playground in C++:

Left shift operator(«) and right shift operator(»), they can make some bits of the left operand shift for the specified bits in the right operand.

  • Syntax

variable « number_of_bits variable » number_of_bits
  • Parameter

variable - (byte, int, long) number_of_bits integer ⇐ 32
  • Example

    int a = 5;        // Binary: 0000000000000101
    int b = a << 3;   // Binary: 0000000000101000, or decimal:40
    int c = b >> 3;   // Binary: 0000000000000101,  or return to the original 5

When you make x shift to the left for y bits(x«y), the left y bits in x will be discarded one by one :


    int a = 5;        // Binary: 0000000000000101
    int b = a << 14;  // Binary: 0100000000000000 - the left 1 is discarded in 101
If you are sure that the displacement won’t cause data overflow, you can simply take the left shift operation as executing the right operand power of 2 to the left operand. 

For example, to generate the power of 2, you can use the following ways:
<pre style="color:green">

1 << 0 == 1
1 << 1 == 2
1 << 2 == 4
1 << 3 == 8
...
1 << 8 == 256
1 << 9 == 512
10 << 1 == 1024
...

When you make x shift to the right for y bits(x»y), if the highest bit of x is 1, the result will depend on the type of x. If the type of x is int, the highest bit is sign bit, which is to say x is negative or positive. Sign bit represents x is negative or positive. In this case, due to the profound historical reasons, the sign bit is copied to the lower bit.


X = -16;    //Binary:1111111111110000
Y = X >> 3  //Binary:1111111111111110

This result is known as the sign extension which is always not what you want. You may want the number to be shifted in the left is 0. The right shift operation will have different result for unsigned int, and you can change the data shifted from the left through forced conversion:


X = -16; //Binary:1111111111110000
int y = (unsigned int)x >> 3;  // Binary: 0001111111111110

If you can carefully avoid sign extension problem, you can take the right shift operation as taking 2 to divide the right operand. For example:


INT = 1000;
Y = X >> 3; 8 1000  //1000 is exactly divided by 8, to make y=125

[Return to Arduino Syntax Manual]