Binary Shift using Python

Did You Know?

Everything that is stored on a computer is stored as binary code. Binary code is made of bits (0 or 1). We often use Bytes to store data. A Byte is made of eight bits and can be used to store any whole number between 0 to 255. Check it yourself, click on the binary digits to create your own binary number:

1286432168421
11111111

128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255


Binary Left Shift


A binary left shift is used to multiply a binary number by two. It consists of shifting all the binary digits to the left by 1 digit and adding an extra digit at the end with a value of 0.
binary-left-shift

Binary Right Shift


A binary right shift is used to divide a binary number by two. It consists of shifting all the binary digits to the right by 1 digit and adding an extra digit at the beginning (to the left) with a value of 0.
binary-right-shift

Multiple-digit Left and Right Shifts


A two-digit left shift consists of two consecutive left shifts on a binary number and is the equivalent of timing this number by 22=4.

A three-digit left shift consists of three consecutive left shifts on a binary number and is the equivalent of timing this number by 23=8. (and so on…)

A two-digit right shift consists of two consecutive right shifts on a binary number and is the equivalent of dividing this number by 22=4.

A three-digit right shift consists of three consecutive right shifts on a binary number and is the equivalent of dividing this number by 23=8. (and so on…)

Python Challenge


The purpose of this challenge is to write a Python script to perform a binary shift. Our Python program will:

  • Ask the user to enter an 8-bit binary number,
  • Ask the user whether they would like to perform a left shift or a right shift,
  • Ask the user whether the number of digits they want to shift,
  • Output the resulting 8-bit binary number.

Test Plan

Test # Input Values Expected Output Actual Output
Binary Number Left/Right Shift? Number of digits
#1 00111100 Left 1 01111000
#2 00111100 Right 1 00011110
#3 00111100 Left 2 111110000
#4 00111100 Right 2 00001111
#5 00001111 Left 3 01111000
#6 00001111 Right 3 0000001

Python Code


Share Button
Posted in Computer Science, Computing Concepts, Python - Intermediate, Python Challenges

Our Latest Book

Follow this blog