Newbie -- bitwise shifts

G

gbblob

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 ?!
 
J

Josiah Carlson

gbblob said:
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
 
J

Jp Calderone

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 ?!
'11'

Jp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top