Python Bitwise Shifts
00:00 In the previous lesson, I covered the bitwise operators AND, OR, and NOT. In this lesson, I’ll show you how to use bitwise shifting. The left and right shift operators move the bits a number of positions to the left or right, respectably. New bits shifted in are of 0 value.
00:21 Because each bit in a binary number is a power of 2, a bit shift is equivalent to a multiplication or division by 2. This is no different than multiplying by 10 in decimal. Shift the digits left and add a 0.
00:48 It is an old-school trick, though, and not really worth it anymore. Optimized compilers know this trick and will do it for you with the added benefit of not confusing the programmer who is maintaining your code.
01:21 No different for non powers of 4. Now, 312 is bigger than a single byte. What if you only want to deal with a single byte? Python doesn’t have a byte data type, but you can emulate it with a bitmask.
01:50 Applying the mask to the bit shift removes any bits above the eighth position, mimicking an eight-bit byte. The bits above the eighth position are gone, and what is left from 312 is the lower eight bits, giving 56 in decimal.
03:02 That is a shift that preserves the sign bit. Think back to those negative numbers I just shifted for you. It felt all reasonable that -16 shifted right by 1 is -8 because of the whole division by 2 thing. But if a 0 had been shifted in on the left side, like with positive numbers, you wouldn’t get -8.
03:50 Other languages automatically choose between arithmetic and logical operators based on the data type the operation is being invoked upon. Python doesn’t support anything but arithmetic, but you could mimic the logical shift with the judicious use of a bitmask.
Become a Member to join the conversation.