Calculate a checksum in Python by applying a specified formula to an explicit sequence of bytes, because “checksum” does not identify one universal algorithm.
Protocols can specify different initial values, byte ranges, widths, reflection rules, complements, byte orders, framing exclusions, and final transformations. The code below therefore exposes three named formulas rather than presenting one generic result: XOR-8 BCC, Modbus ASCII two's-complement LRC, and raw byte sum modulo 256. Use only the output required by the target documentation.

Select the checksum your protocol requires
The word “BCC” alone is not enough to identify an algorithm. A vendor may use BCC for an XOR calculation, an additive checksum, LRC, CRC, or a checksum covering a different part of the frame. Likewise, an LRC may use another initialization or transformation outside the Modbus ASCII definition. Check the protocol specification for the algorithm, covered fields, initial value, result width, final complement, and transmitted byte order.
BALTECH’s XOR-8 BCC reference is useful because it states the eight-bit XOR rule explicitly. Confirm both that operation and the exact fields covered by the vendor. For standard Modbus ASCII, the MODBUS over Serial Line Specification V1.02 excludes the starting colon and ending CRLF from the bytes supplied to the LRC calculation.
| Output | Calculation | Important rule |
|---|---|---|
| XOR-8 BCC | Start at zero and XOR every covered byte into an eight-bit accumulator. | Carries do not apply, but the selected byte set must match the specification. |
| Modbus ASCII LRC | Add the covered bytes modulo 256, then return the negative final sum modulo 256. | Standard Modbus ASCII excludes the starting colon and ending CRLF. |
| Raw byte sum modulo 256 | Add the covered bytes and retain the low eight bits. | This is a diagnostic intermediate, not automatically the transmitted checksum. |
If XOR-8 is new to you, How to Calculate a BCC Checksum for Beginners explains the accumulator pattern before you adapt it to a protocol-specific byte list.
Build the exact payload bytes
A Python checksum operates on bytes, not abstract characters. Choose the representation used by the protocol documentation and convert the payload explicitly. This avoids platform-dependent text encoding and makes it possible to compare the Python result with a device or test vector.
| Input | Python conversion | Rule to preserve |
|---|---|---|
| Text | text.encode("utf-8") | Encode explicitly as UTF-8; one visible character can produce several bytes. |
| Hexadecimal | bytes.fromhex(hex_text) | Use exactly two hex digits per byte, with optional whitespace between bytes. |
Python’s bytes.fromhex() rejects malformed pairs, odd-length input, prefixes such as 0x, and punctuation such as commas, colons, or dashes. Comments and other non-hex characters are also invalid. This strict behavior is useful because it prevents a malformed frame from being silently guessed.
After conversion, check len(data) against the expected byte count. The number of bytes can differ from the number of visible characters when UTF-8 text contains non-ASCII symbols. Also keep checksum coverage separate from framing: enter only the fields named by the specification rather than an entire displayed message by habit.
Calculate a checksum in Python
-
Confirm the formula and covered bytes. Read the target documentation before coding. Identify the checksum width, algorithm, initial value, included fields, any complement, and transmitted byte order. For standard Modbus ASCII, use the message bytes without the starting colon or ending CRLF.
-
Create a byte sequence. Use text.encode("utf-8") for text or bytes.fromhex(hex_text) for hexadecimal. Verify its length before applying the checksum.
-
Apply the explicit formulas. This Python implementation returns all three labeled values over the same bytes, allowing you to select the one required by the protocol.
Python implementation:
def checksum_values(data: bytes):
total = sum(data) % 256
bcc = 0
for byte in data:
bcc ^= byte
return {"xor8_bcc": bcc, "modbus_lrc": (-total) % 256, "sum_mod_256": total}
-
Run the function and format each result. The 02x format produces two lowercase hexadecimal digits and preserves a leading zero.
payload = bytes.fromhex("31 32")
results = checksum_values(payload)
print({name: f"{value:02x}" for name, value in results.items()})
For this one example, the calculations are:
- Raw byte sum: (0x31 + 0x32) modulo 256 = 0x63.
- XOR-8 BCC: 0x31 XOR 0x32 = 0x03.
- Modbus ASCII LRC: negative 0x63 modulo 256 = 0x9d.
The formatted results are xor8_bcc: 03, modbus_lrc: 9d, and sum_mod_256: 63. Do not transmit all three simply because the function returns them; select the label required by the protocol.
-
Compare against an authoritative value. Use a documented test vector, known-good frame, or device reference to validate the implementation and byte selection. If the values disagree, revisit the covered fields and algorithm definition before changing formulas.
Verify the same bytes in the browser
The Checksum Calculator mirrors these three explicit formulas and can help verify a Python result without changing the input interpretation.
- Choose UTF-8 text or hexadecimal bytes according to the protocol’s actual representation.
- Enter exactly the bytes covered by the checksum, omitting framing only when the target specification says to do so.
- Run the calculation and compare the labeled XOR-8 BCC, Modbus ASCII LRC, and raw sum values with the Python output.
- Check that both methods report the same processed byte count, then copy the labeled result for a diagnostic note or record.
The calculator processes the input locally, shows two lowercase hex digits for every result, and never silently truncates data. It accepts at most 500,000 bytes and reports malformed hexadecimal input without producing a partial value. In text mode, the browser encodes the string as UTF-8 first, so a multi-byte character can increase the displayed byte count beyond the visible character count.
Read the three results correctly
XOR-8 BCC is order-independent because XOR is commutative, and carries are irrelevant. That does not make the field selection optional: adding or removing a covered byte changes the result unless that byte is 0x00. Modbus ASCII LRC behaves differently because it sums the bytes, discards carries, and applies a final two’s-complement step. The raw sum modulo 256 shows the value before that complement.
For the implemented Modbus ASCII two’s-complement LRC, the raw sum and the LRC add to zero modulo 256. Seeing both labeled values makes it easier to determine whether a device description expects an additive total, its complement, or another convention. The calculation determines the value only; the target documentation determines where and in what byte order the checksum is transmitted.
Diagnose byte and framing mismatches
When a calculated value does not match, compare the inputs before replacing the formula.
- Representation: Confirm that one side uses text and the other uses explicit bytes.
- Encoding: Require UTF-8 whenever text is converted to bytes.
- Byte count: Compare the processed lengths, especially for non-ASCII text.
- Framing: For standard Modbus ASCII, remove the starting colon and ending CRLF from the LRC input.
- Field coverage: Include only the address, function, data, or other fields named by the protocol.
- Transformation: Distinguish raw sum, two’s-complement LRC, XOR-8, and CRC-style outputs, and check the required byte order.
Do not switch algorithms merely to make two results match. The device documentation remains the authority for the intended convention.
Use checksums for error detection, not authentication
These one-byte checks can detect some accidental changes, but they are not cryptographic hashes, message authentication codes, digital signatures, or proof of origin. XOR and additive checksums have many collisions and can be deliberately adjusted, so they must not protect credentials, authorize commands, verify software downloads, or authenticate hostile network traffic.
The implementation and calculator are also intentionally limited. If the protocol specifies CRC-16, CRC-32, Fletcher, Adler, an Internet checksum, or a named cryptographic hash, use the exact algorithm required by that specification instead of substituting one of these one-byte values.
For a deeper look, see HMAC Generator on Windows: Exact Tags in Your Browser.