Instantly share code, notes, and snippets.

Embed
What would you like to do?
from PyCRC.CRCCCITT import CRCCCITT
from PyCRC.CRC32 import CRC32
from PyCRC.CRC16 import CRC16
from PyCRC.CRC16DNP import CRC16DNP
from PyCRC.CRC16Kermit import CRC16Kermit
from PyCRC.CRC16SICK import CRC16SICK
src = [
# 'surface_galaxy.bmp',
'surface_01_red_arron.bmp'
]
def crc16_ccitt_direct(crc, data):
msb = crc >> 8
lsb = crc & 255
for c in data:
# x = ord(c) ^ msb
x = c ^ msb
x ^= (x >> 4)
msb = (lsb ^ (x >> 3) ^ (x << 4)) & 255
lsb = (x ^ (x << 5)) & 255
return (msb << 8) + lsb
POLYNOMIAL = 0x11021
PRESET = 0
def _initial(c):
crc = 0
c = c << 8
for j in range(8):
if (crc ^ c) & 0x8000:
crc = (crc << 1) ^ POLYNOMIAL
else:
crc = crc << 1
c = c << 1
return crc
def _update_crc(crc, c, _tab):
cc = 0xff & c
tmp = (crc >> 8) ^ cc
crc = (crc << 8) ^ _tab[tmp & 0xff]
crc = crc & 0xffff
# print (crc)
return crc
def calc_manu(bs, present = PRESET):
'''
x^16+x^12+x^5+1
unsigned short crc16(const unsigned char* data_p, unsigned char length)
{
unsigned char x;
unsigned short crc = 0xFFFF;
while (length--)
{
x = crc >> 8 ^ *data_p++;
x ^= x>>4;
crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
}
return crc;
}
'''
# return crc16_ccitt_direct(0, bs)
_tab = [ _initial(i) for i in range(256) ]
crc = present
for b in bs:
crc = _update_crc(crc, b, _tab)
return crc
# bs = [0x0,0x1,0x2,0x3,0x4,0x5]
bimage = open(src[0], 'rb').read(90000)
print(src[0] + ": " +str(len(bimage)))
print("CRCCCITT: " + hex(CRCCCITT().calculate(bimage)))
print("manu: " +hex(calc_manu(bimage)))
print("FFFF: " +hex(calc_manu(bimage, present = 0xFFFF)))
bs = '123456'.encode('utf-8')
print(str(bs) + ": " +str(len(bs)))
print("CRCCCITT: " + hex(CRCCCITT().calculate(bs)))
print("manu: " +hex(calc_manu(bs)))
print("FFFF: " +hex(calc_manu(bs, present = 0xFFFF)))
# print("CRCCCITT" + hex(CRCCCITT().calculate(bs)))
# for s in src:
# bs = open(s, 'rb').read(90000)
# # print(len(bs))
# print(s + ": " +hex(CRCCCITT().calculate(bs)))
# print("manu: " +hex(calc_manu(bs)))
# print("CRC32:" + hex(CRCCCITT().calculate(bs)))
# print("CRC16:" + hex(CRC16().calculate(s)))
# print("CRC16DNP:" + hex(CRC16DNP().calculate(s)))
# print("CRC16Kermit:" + hex(CRC16Kermit().calculate(s)))
# print("CRC16SICK:" + hex(CRC16SICK().calculate(s)))
'''
surface_01_red_arron.bmp: 86454
CRCCCITT: 0x2d2f
manu: 0x2d2f
FFFF: 0x9c92
b'123456': 6
CRCCCITT: 0x20e4
manu: 0x20e4
FFFF: 0x2ef4
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment