Skip to content

Commit 99c97bb

Browse files
authored
[Term Entry] Python binascii-module: .crc_hqx()
* docs: Add Python binascii.crc_hqx() term entry (#7733) * content changes * Minor changes ---------
1 parent 645c9a9 commit 99c97bb

File tree

1 file changed

+76
-0
lines changed
  • content/python/concepts/binascii-module/terms/crc-hqx

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
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

Comments
 (0)