Ruby实现计算CRC16校验码
#计算CRC16
def crc(num)
crcnum=0xFFFF
num.each do|i|
crcnum=crcnum^((i.to_i)&0x00ff)
1.upto(8) do
if (crcnum&0x0001)!=0 then
crcnum=(crcnum>>1)^0x8005
else
crcnum=crcnum>>1
end
end
end
return crcnum
end
#测试
#要计算的数据
dd=[20, 03, 01, 40, 00, 15]
sum= crc(dd)
#打印结果
puts "十进制:"+ sum.to_s
puts "十六进制:0x"+ sum.to_s(16)
#获取低8位
puts "0x"+ ((sum>>0)&0x00FF).to_s(16)
#获取高8位
puts "0x"+ ((sum>>8)&0x00FF).to_s(16)