Last active
February 20, 2024 17:26
-
-
Save callumbrieske/2f01241918c065fd0636e490c56a545e to your computer and use it in GitHub Desktop.
Module 256 checksums
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data = "\x00\x00\x02\x02\x00" | |
local function modulo( data ) | |
local checksum = 0 | |
for _, byte in ipairs( table.pack( data:byte( 1, #data ) ) ) do | |
checksum = ( checksum + byte ) % 256 | |
end | |
return string.char( checksum ) | |
end | |
local function twosComplimentModulo( data ) | |
local checksum = 0 | |
for _, byte in ipairs( table.pack( data:byte( 1, #data ) ) ) do | |
checksum = ( checksum + byte ) % 256 | |
end | |
return string.char( (256 - checksum) % 256 ) | |
end | |
-- Use example: | |
checksum = twosComplimentModulo( data ) | |
-- or | |
checksum = twosComplimentModulo( "This is my string!" ) | |
-- The functions all return a 'char', so to get a byte you need to do a string.byte. | |
-- This will print a 'hex' representation. | |
print( string.format( "\\x%02X", string.byte( twosComplimentModulo( data ) ) ) ) | |
print( string.format( "\\x%02X", string.byte( modulo( data ) ) ) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment