|
| 1 | +--- |
| 2 | +Title: '.crc_hqx()' |
| 3 | +Description: 'Computes a 16-bit CRC (CRC-CCITT) checksum of binary data using the CRC-HQX algorithm.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Algorithms' |
| 9 | + - 'Functions' |
| 10 | +CatalogContent: |
| 11 | + - 'learn-python-3' |
| 12 | + - 'paths/computer-science' |
| 13 | +--- |
| 14 | + |
| 15 | +The **`.crc_hqx()`** function in Python’s built-in `binascii` module computes a 16-bit Cyclic Redundancy Check (CRC) value using the CRC-HQX algorithm, commonly used in the original Mac OS. |
| 16 | + |
| 17 | +This checksum helps detect errors in data transmission or storage by verifying that the received data matches the original data. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +binascii.crc_hqx(data, value) |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +- `data` (bytes-like object): The binary data for which the CRC value is computed. |
| 28 | +- `value` (integer): An optional 16-bit starting value for the checksum calculation. If omitted, the initial value is `0`. |
| 29 | + |
| 30 | +**Return value:** |
| 31 | + |
| 32 | +Returns a 16-bit integer representing the computed CRC checksum of the input data, according to the CRC-HQX algorithm. |
| 33 | + |
| 34 | +## Example |
| 35 | + |
| 36 | +In this example, the checksum is computed for a byte string, once with a non-zero starting value and once with an initial value of `0`: |
| 37 | + |
| 38 | +```py |
| 39 | +import binascii |
| 40 | + |
| 41 | +data = b"Codecademy Docs" |
| 42 | +initial_crc = 0xAAAA # A common non-zero starting value |
| 43 | + |
| 44 | +# 1. Compute CRC with a starting value (0xAAAA) |
| 45 | +crc_with_initial = binascii.crc_hqx(data, initial_crc) |
| 46 | + |
| 47 | +# 2. Compute CRC starting from 0 |
| 48 | +crc_without_initial = binascii.crc_hqx(data, 0) |
| 49 | + |
| 50 | +print(f"Data: {data!r}") |
| 51 | +print(f"CRC (with initial value 0xAAAA): 0x{crc_with_initial:04x}") |
| 52 | +print(f"CRC (starting from 0): 0x{crc_without_initial:04x}") |
| 53 | +``` |
| 54 | + |
| 55 | +The output of this code is: |
| 56 | + |
| 57 | +```shell |
| 58 | +Data: b'Codecademy Docs' |
| 59 | +CRC (with initial value 0xAAAA): 0x134c |
| 60 | +CRC (starting from 0): 0x67ce |
| 61 | +``` |
| 62 | + |
| 63 | +## Codebyte Example |
| 64 | + |
| 65 | +This example below computes the CRC-HQX checksum for a byte string using a starting value of `0`: |
| 66 | + |
| 67 | +```codebyte/python |
| 68 | +import binascii |
| 69 | +
|
| 70 | +data_to_check = b"Python Contributor" |
| 71 | +
|
| 72 | +# Calculate the CRC-HQX checksum starting from 0 |
| 73 | +checksum = binascii.crc_hqx(data_to_check, 0) |
| 74 | +
|
| 75 | +print(f"Checksum: 0x{checksum:04x}") |
| 76 | +``` |
0 commit comments