Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit shifting in python

I want to understand the following code. What kinda shifting 3rd line is doing?

number = 1.265
bits = 8
shifted_no = 1.265 * (2** bits)

If I check the binary format of the results of number and shifted_no :

0011 1111 1010 0001 1110 1011 1000 0101
0100 0001 0010 0001 1110 1011 1000 0101

Thanks.

like image 718
blackbug Avatar asked Jan 17 '26 22:01

blackbug


1 Answers

If i is an integer,

i * 2**bits

is equal to

i << bits

As an example :

>>> 1 * 2**8
256
>>> 1 << 8
256
>>> 2 * 2**8
512
>>> 2 << 8
512

But << isn't defined for floats :

>>> 1.265 << 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'float' and 'int'

You can think of :

* 2**bits

as being an extension of << bits to floats. :

>>> 1.0 * 2**8
256.0
>>> 1.00000000001 * 2**8
256.00000000256
>>> 1.265 * 2**8
323.84
>>> 1.99999999999 * 2**8
511.99999999744
>>> 2.0 * 2**8
512.0

As a comparison, n! is only defined for non-negative integers but Γ(z) is defined for any complex number and coincides with the factorial function when plugging in a natural number. See this thread.

like image 154
Eric Duminil Avatar answered Jan 19 '26 14:01

Eric Duminil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!