Reputation: 487
I'm trying to calulate CRC-CCITT (0xFFFF) for HEX string and get result back as HEX string. I tried binascii
and crc16
but I get int values and when I convert them to HEX it's not the value I expected. I need this:
hex_string = "AA01"
crc_string = crccitt(hex_string)
print("CRC: ", crc_string)
>>> CRC: FF9B
Upvotes: 1
Views: 6679
Reputation: 368894
You can use str.format
/ format
to convert the int value to hexadecimal format: (used crc16
to get crc)
>>> import binascii
>>> import crc16
>>> hex_string = 'AA01'
>>> crc = crc16.crc16xmodem(binascii.unhexlify(hex_string), 0xffff)
>>> '{:04X}'.format(crc & 0xffff)
'FF9B'
>>> format(crc & 0xffff, '04X')
'FF9B'
or using %
operator:
>>> '%04X' % (crc & 0xffff)
'FF9B'
import binascii
import crc16
def crccitt(hex_string):
byte_seq = binascii.unhexlify(hex_string)
crc = crc16.crc16xmodem(byte_seq, 0xffff)
return '{:04X}'.format(crc & 0xffff)
Upvotes: 2