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/
'프로그래밍 > Python' 카테고리의 다른 글
[python] socketio Clinet : One or more namespaces failed to connect error (0) | 2021.09.28 |
---|---|
flask RESTful API의 CORS 설정 (0) | 2021.09.09 |
[python] 크롬 브라우저 실행 방법 (0) | 2021.08.09 |
[Python] email-"The sender address is not a valid RFC-5322 address" 오류 대처 (0) | 2021.08.05 |
[python] JSON 검증 (validation) (0) | 2021.06.19 |