bit shifting question

Michael Hudson mwh at python.net
Mon May 17 15:22:33 EDT 2004


"David Stockwell" <winexpert at hotmail.com> writes:

> Hi,
> My background is c/c++ and java.  I'm learning python at this point.
> 
> My question is does python share java's peculiar mode of bit shifting,
> or does python adhere closer to c's bit shifting?

The right shift in Python is arithmetic, i.e. preserves the sign bit.

> in java there are 3 kinds of bit shifts:
>   <<      (shift left)
>   >>     (preserve the sign bit as we move right )
>   >>>   (0 filled on the left as we move right)
> 
> In C, the behavior is
>   <<  (shift left)
>    >> (shift right , 0 filled  (like java's >>>'))

Have you tried this recently?  I believe that whether >> sign fills is
undefined by the C standard but most of the time it dos.

> I tried looking around but haven't really got an answer yet.  I guess
> I need to write a mini python script.

No you don't!  If you haven't realized that you can do

$ python
Python 2.2.2 (#1, Feb 24 2003, 19:13:11) 
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> (-1) >> 3
-1

you have MUCH to learn about Python...

Cheers,
mwh

-- 
  Python enjoys making tradeoffs that drive *someone* crazy <wink>.
                                       -- Tim Peters, comp.lang.python



More information about the Python-list mailing list