프로그래밍/Python

CCITT CRC16 함수

채윤아빠 2021. 9. 6. 16:26
728x90
반응형

CCITT CRC16() 함수를 소개해 드립니다.

# CCITT CRC16
# made : hbesthee@naver.com
# date : 2021-09-06
# reference : https://stackoverflow.com/questions/25239423/
#    https://crccalc.com/

POLYNOMIAL = 0x1021
PRESET = 0xFFFF

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

_tab = [ _initial(i) for i in range(256) ]

def _update_crc(crc, c):
    cc = c & 0xff

    tmp = (crc >> 8) ^ cc
    crc = (crc << 8) ^ _tab[tmp & 0xff]
    crc = crc & 0xffff
    #print (crc)

    return crc

def crc16bytes(data_bytes):
    crc = PRESET
    for byte in data_bytes:
        crc = _update_crc(crc, (byte))
    return crc

def crc16str(str):
    crc = PRESET
    for c in str:
        crc = _update_crc(crc, ord(c))
    return crc

def crc16(*data):
    crc = PRESET
    for item in data:
        crc = _update_crc(crc, (item))
    return crc

if __name__ == '__main__':
    print(hex(crc16bytes(b'123456789')))
    print(hex(crc16str('123456789')))
    print(hex(crc16(0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39)))

결과값에 대한 검증은 https://crccalc.com/ 에서 하시면 됩니다.


참고자료 : https://stackoverflow.com/questions/25239423/