Skip to content

Instantly share code, notes, and snippets.

@rdp
Last active November 6, 2023 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdp/3940102 to your computer and use it in GitHub Desktop.
Save rdp/3940102 to your computer and use it in GitHub Desktop.
crc32c for ruby
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
@rdp
Copy link
Author

rdp commented Mar 24, 2020

NB that some implementations do the bytes in the reverse order than this :| (LT08 is reverse this, T10K uses the above)

@adsr
Copy link

adsr commented Nov 6, 2023

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