I am new to C++, but I have to write a simple program to calculate the CRC16 of a Modbus string.
I have only to write that, I have not to do anything else.
The program writed in Python is the following:
[coode]
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)
[/code]
For example, with the string "11010003000C" the output of the conversion must be "CE9F".
I need only that function for my first and I think only program in C++.
Let's try a different approach. This python function looks a little sparse for something like redundancy checking so we're going to drop it on the floor and look at a C\C++ solution instead. Check here: https://github.com/d-bahr/CRCpp .Why is it only 16-bit? Is that a requirement?
Bokka, i call BS, that's not Python. Python is all about indentation, and your post is completely left-aligned. Can't even tell when the nested(?) for loops end.
The zip() with extended slices of 2 just assigns "op" to every even index element of data, and "code" to every odd index of data. The zip seems unnecessary to me since it's zipping from the same array. Then again, I come from Ruby background, not python.
The range() is just up to but not including bits. So a normal indexed loop.
Upon closer inspection, "op" and "code" are basically unused. They just wanted the substring of every two characters. std::hex returns lowercase hex by default, so that's why std::uppercase is employed here as well.