You are almost there.
Here is the fix:
class CRC16
def CRC16.CalculateCrc16(data)
crc = 0
temp = 0
i = 0
while i < data.length # Modified from OP version
value = data[i]
temp = (value ^ (crc >> 8))
temp = (temp ^ (temp >> 4))
temp = (temp ^ (temp >> 2))
temp = (temp ^ (temp >> 1))
crc = (((crc << 8) ^ (temp << 15) ^ (temp << 2) ^ temp))
crc &= 0xffff # New - keep integer in "unsigned short" bit space
i += 1
end
return crc
end
end
I changed just two things to make it work as per the C version:
Length
->length
, a typo- Ruby doesn't do
short
, or any other kind of restriction on integer size. You have to add it. That is whatcrc &= 0xffff
is doing. Without it, bits shifted "out" of the short come back to haunt you and give a nonsense result.
In addition, I replaced 0x0000
with 0
, as it looked like an attempt to get Ruby to treat the integers as "short", which is not possible this way.