Please, someone could help me to convert a function from Python to Swift 4?

Hello I have to port a very simple application from Python to Swift, but I can’t understand how to convert that function:

 

def crc16(data, bits=8):
    crc = 0xFFFF
    for op, code in zip(data[0::2], data[1::2]):
        crc = crc ^ int(op+code, 16)
        for bit in range(0, bits):
            if (crc&0x0001)  == 0x0001:
                crc = ((crc >> 1) ^ 0xA001)
            else:
                crc = crc >> 1
    msb = crc >> 8
    lsb = crc & 0x00FF
    return '{:X}{:X}'.format(lsb, msb)

 

And the result is shown by that code:

 

print crc16('11010003000C')

 

 

The code have to calculate the CRC16 of a string.

 

For example, for the string:

 

11 01 00 03 00 0C

 

The CRC calculated must be

 

CE9F (CE High, 9F Low)

 

And for the string

 

 

11 01 02 CD 0B

 

The result of the CRC must be

 

6D 68

 

I’m trying to make some steps, but I am far away from the results….

 

There is a way to write it in swift?

Powered by WPeMatico

About

You may also like...

Comments are closed.