Last active
November 6, 2023 17:51
-
-
Save rdp/3940102 to your computer and use it in GitHub Desktop.
crc32c for ruby
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
require 'digest/crc32c' # gem install digest-crc | |
p 'syntax: something to get digested! [output it with trailing 4 byte digest, in ruby string syntax]' | |
checksum = Digest::CRC32c.checksum(ARGV[0]) | |
p checksum | |
out = ARGV[0].dup.bytes # assume it starts ascii :| | |
for n in [24, 16, 8, 0] | |
next_byte = (checksum >> n & 0xff) | |
out << next_byte | |
p "x%x" % next_byte | |
end | |
p out | |
p 'total bytes:' | |
p out.to_a.join(',') | |
File.open("raw_bytes", "wb") do |f| | |
out.each{|b| | |
f.print b.chr | |
} | |
end | |
puts "wrote raw_bytes file" # can send to tape device or what have you |
If I'm reading this correctly, this is reversing the byte order, which can be done more succinctly with Ruby's built-in pack
:
cksum = Digest::CRC32c.file(filepath).checksum # or Digest::CRC32c.checksum(string)
cksum_big_endian = [cksum].pack('L>') # pack as 32-bit BE int
# `cksum_big_endian` is a raw byte string
Base64.encode64(cksum_big_endian).chomp # These checksums are commonly expressed in base64 encoding
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NB that some implementations do the bytes in the reverse order than this :| (LT08 is reverse this, T10K uses the above)