python shift operator uses

Question:

Im just learning about pythons bitwise operator << and >>. as far as I see, it takes the binary version of an integer and shifts it n places left or right. that would mean that saying x<<y is equivalent to x*(2**y)

so my question is why is there an operator for this? as far as I know python doesnt like to give you more than 1 way of doing things to avoid confusion. is there a reason this operator is particularly useful or typical scenerios where its used? I know this is a pretty open ended question but when searching for this I only come across what this operator does, not why we would use it. thankyou in advance

Asked By: Christian Trujillo

||

Answers:

The key is in your remark "it takes the binary version of an integer and shifts it n places left or right".

Ask yourself this: how does your computer represent integers at all? What are integers? Any integer is a sequence of bits, (typically a multiple of 8 bits, i.e. a byte) and your computer is built around memory positions, registers, addresses, etc. that hold these integer values.

So, it makes sense for a CPU to have an operation to shift such a value left or right by one bit, for an extremely fast multiplication or division by 2, more so since powers of two are very commonly needed because everything in your computer is binary.

Other operations can be composed from simple addition, subtraction, shift by n, etc. – Python exposes this operation to give you access to this very basic and quick operation, although Python integers aren’t always (or even all that often) the same efficient integers you operate on directly in many other languages.

But bit-shifting has many applications, and as a standard operation of your computer, it only makes sense that Python would give you access to a tool that programmers are very used to, and have applications for in many common algorithms.

Answered By: Grismar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.