Newbie -- bitwise shifts
Josiah Carlson
jcarlson at nospam.uci.edu
Wed Feb 4 16:31:32 EST 2004
gbblob wrote:
> Can someone please explain to me why left shits are equivalent to
> multiplication and right shifts equivalent to devision? This seems
> backwards to me.
>
> e.g.
>
> 15 is binary 1111
> if I shift this left 2 bits I get 11
>
> however in Python 15<<2 = 60 ?!
In computer science, shifting a number 'k' bits to the left, is the same
as adding 'k' zeroes to the right side. Shifting a number 'j' bits to
the right, is the same as removing 'j' digits from the right side.
15<<2 == 15 * 2**2
15>>2 == 15 // 2**2
This has been the way of things since at least the 1950's.
- Josiah
More information about the Python-list
mailing list