Bitwise left 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 operands.

  • 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 left for y bits(x«y), the y bits in the left of x will be discarded one by one:


    int a = 5;        // Binary: 0000000000000101
    int b = a << 14;  // Binary: 0100000000000000 - the left 1 in 101 is discarded
If you can’t confirm whether the displacement can cause data overflow, you can just take 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 methods:
<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 right for y bits(x»y), if the highest bit of x is 1, the result will depend on the data type of x. If the type of x is int, the highest bit is sign bit that says x is positive or negative, just as what we talked above. In this case, due to the profound historical reason, the sign bit is copied to the relatively low 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 shifted in the left is 0. Right shift operation will have different result for unsigned int, and you can change the data shifted in from the left through the data forced conversion:


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

If you can carefully avoid the sign extension problem, you can take the right shift operation as the calculation of taking 2 to divide the data, for example :


INT = 1000;
Y = X >> 3; 8 1000  //1000 is exactly divided by 8, to make y=125
[Return to Arduino Syntax Manual]