Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

3. Using Mathematical Operators > 3.13. Shifting Bits

3.13. Shifting Bits

Problem

You need to perform bit operations that shift bits left or right in a byte, int, or long.

Solution

Use the << (bit-shift left) and >> (bit-shift right) operators to shift the bits of a value.

Discussion

This fragment sets variable x equal to 6. It shifts the bits left by one and prints the new value (12). Then that value is shifted right two places (and in this example becomes equal to 3):

int x = 6;
int result = x << 1;  // 6  shifted left 1 is 12
Serial.println(result);
int result = x >> 2;   // 12 shifted right 2 is 3;
Serial.println(result);

Here is how this works: 6 shifted left one place equals 12, because the decimal number 6 is 0110 in binary. When the digits are shifted left, the value becomes 1100 (decimal 12). Shifting 1100 right two places becomes 0011 (decimal 3). You may notice that shifting a number left by n places is the same as multiplying the value by 2 raised to the power of n. Shifting a number right by n places is the same as dividing the value by 2 raised to the power of n. In other words, the following pairs of expressions are the same:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint