ElEscalador
Posts: 598
Joined: Tue Dec 15, 2015 4:55 pm
Location: Detroit, MI USA
Contact: Website

Help a brother understand this Python code

Mon Aug 20, 2018 10:07 pm

I think I get a lot of it, but what exactly does the >> and << do?
And if I understand correctly, data_list[] will end up with 5 members, so the "for d in data_list:" part means the next line will execute 5 times?
I have very limited exposure to python and am trying to convert this to something usable in c++

Code: Select all

def checksum(data):
    """Compute and return the checksum as an int."""
    # group the data by word, little-endian
    data_list = []
    for t in range(10):
        data_list.append( data[2*t] + (data[2*t+1]<<8) )
 
    # compute the checksum on 32 bits
    chk32 = 0
    for d in data_list:
        chk32 = (chk32 << 1) + d
 
    # return a value wrapped around on 15bits, and truncated to still fit into 15 bits
    checksum = (chk32 & 0x7FFF) + ( chk32 >> 15 ) # wrap around to fit into 15 bits
    checksum = checksum & 0x7FFF # truncate to 15 bits
    return int( checksum )
My Autonomous Robot Project and a few of my other projects below.

https://lloydbrombach.wordpress.com/

User avatar
PeterO
Posts: 4237
Joined: Sun Jul 22, 2012 4:14 pm

Re: Help a brother understand this Python code

Mon Aug 20, 2018 10:09 pm

<< and >> do the same in Python as they do in C.

https://wiki.python.org/moin/BitwiseOperators

PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),Aeromodelling,1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

ElEscalador
Posts: 598
Joined: Tue Dec 15, 2015 4:55 pm
Location: Detroit, MI USA
Contact: Website

Re: Help a brother understand this Python code

Tue Aug 21, 2018 12:47 am

Ahh...I've actually never used them. Er...maybe I have but I copied them without understanding them. But got it all now, thank you for the education.
My Autonomous Robot Project and a few of my other projects below.

https://lloydbrombach.wordpress.com/

Return to “Python”

Who is online

Users browsing this forum: No registered users and 15 guests