Preview lessons, content and tests

Computer Science & Programming solved. All in one platform.

1. To trial the platform and take tests, please take a few seconds to SIGN UP and SET UP FREE.
2. Searching for something specific? See our text overview of all tests. Scroll right for levels, and lists.

Join 36000+ teachers and students using TTIO.

Binary Shift

Binary shifting is a simple but useful method of bit manipulation, often used alongside bitwise logical operations.

A normal bit shift operation is sometimes called a logical shift, because it treats the byte as a set of independent logical bits. The alternative is an arithmetic shift, which treats the byte as a number.

The examples here all use bytes. You can also apply the same technique to 16-bit words, 32-bit words or any other word size.

Suggested Video

Logical shift left

The shift left operation shifts each bit one place to the left:

Shift Left bit 1

  • What was in bit position 0 moves to bit position 1.
  • What was in bit position 1 moves to bit position 2.
  • etc…
  • What was in bit position 7 (the left most bit) falls off the end and is lost forever.
  • A 0 is moved into bit position 0.

You will notice in the example, the byte originally had a denary value 29. After the shift, it has a denary value 58, which is exactly twice as much as its original value. That will always be the case.

It shouldn’t be a surprise, because a similar thing happens in base 10. If we take the number 237 and shift each digit 1 place to the left, adding a zero to the right hand side, we get 2370. This is, of course, 10 times the starting value - that is how you multiply things by 10. In binary, left shifting multiplies by 2, not 10, because we are working in base 2.

 

www.teachyourselfpython.com