The left-shift moves the bit to the left, and right-shift move to the right.
Shift operators |
Coding
The following shifts a binary value to the left and right by one bit position:
import sys val1="00110101" if (len(sys.argv)>1): val1=sys.argv[1] print ("Binary form: \t\t",val1) dec=int(val1,2) print ("Decimal form: \t\t",dec,"\t",bin(dec)[2:10].rjust(8,'0')) res=(dec << 1) & 0xff print ("Shift left (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0')) res=(dec << 2) & 0xff print ("Shift left (2):\t",res,"\t",bin(res)[2:].rjust(8,'0')) res=(dec >> 1) & 0xff print ("Shift right (1):\t",res,"\t",bin(res)[2:10].rjust(8,'0')) res=(dec >> 2) & 0xff print ("Shift right (2):\t",res,"\t",bin(res)[2:10].rjust(8,'0'))
Sample run
A sample run is:
Binary form: 00110101 Decimal form: 53 00110101 Shift left (1): 106 01101010 Shift left (2): 212 11010100 Shift right (1): 26 00011010 Shift right (2): 13 00001101
Coding here: