>> and << operators?

Discussion in 'Python' started by defn noob, Aug 22, 2008.

  1. defn noob

    defn noob Guest

    What does >> and << do?

    Googling on them and they are just ignored...
    defn noob, Aug 22, 2008
    #1
    1. Advertising

  2. On Fri, Aug 22, 2008 at 6:30 PM, defn noob <> wrote:
    > What does >> and << do?


    Normally they are bitwise operators:
    >> Shifts bits right

    << Shifts bits left

    print 1 << 3
    8

    because 8 = 00001000 in binary

    Regards
    Medardo Rodriguez (Merchise Group), Aug 22, 2008
    #2
    1. Advertising

  3. defn noob

    Mensanator Guest

    On Aug 22, 5:43 pm, "Medardo Rodriguez (Merchise Group)"
    <> wrote:
    > On Fri, Aug 22, 2008 at 6:30 PM, defn noob <> wrote:
    > > What does >> and << do?

    >
    > Normally they are bitwise operators:>> Shifts bits right
    >
    > << Shifts bits left
    >
    > print 1 << 3
    > 8
    >
    > because 8 = 00001000 in binary
    >
    > Regards


    An example of usage:

    import gmpy
    def Collatz(n):
    #
    # if n is odd, multiply by 3 and add 1
    # if n is even, divide by 2 until n becomes odd
    # repeat until n == 1
    #
    while n>1:
    print n,
    f = gmpy.scan1(n) # find position of first 1-bit
    if f>0: # it's even, so...
    n = n >> f # ...remove factors of 2 in one fell swoop
    else: # it's odd
    n = 3*n + 1
    print n

    print 'Collatz(11):',
    Collatz(11)

    print

    print 'Collatz(27):',
    Collatz(27)

    ## Collatz(11): 11 34 17 52 13 40 5 16 1
    ##
    ## Collatz(27): 27 82 41 124 31 94 47 142 71
    ## 214 107 322 161 484 121 364
    ## 91 274 137 412 103 310 155
    ## 466 233 700 175 526 263 790
    ## 395 1186 593 1780 445 1336
    ## 167 502 251 754 377 1132 283
    ## 850 425 1276 319 958 479 1438
    ## 719 2158 1079 3238 1619 4858
    ## 2429 7288 911 2734 1367 4102
    ## 2051 6154 3077 9232 577 1732
    ## 433 1300 325 976 61 184 23 70
    ## 35 106 53 160 5 16 1
    Mensanator, Aug 23, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JamesW

    Strings and Operators

    JamesW, Feb 20, 2004, in forum: Perl
    Replies:
    2
    Views:
    467
  2. Dean Mitchell
    Replies:
    4
    Views:
    378
    Attila Feher
    Aug 27, 2003
  3. Philip Müller
    Replies:
    4
    Views:
    104
    Robert Klemme
    Apr 18, 2009
  4. Iain Barnett
    Replies:
    0
    Views:
    88
    Iain Barnett
    Feb 2, 2011
  5. Replies:
    0
    Views:
    96
Loading...

Share This Page