How to calculate the CRC32 of a string in Ruby

1 Answer

0 votes
require "zlib"

# Calculates the CRC32 checksum of a string.
# Returns an 8‑character uppercase hexadecimal string.
def crc32_of_string(text)
  # Zlib.crc32 computes the standard CRC‑32 checksum.
  # It returns a signed 32‑bit integer on some systems,
  # so we mask with 0xFFFFFFFF to ensure an unsigned result.
  crc = Zlib.crc32(text) & 0xFFFFFFFF

  # Format as 8‑digit uppercase hexadecimal (standard CRC32 format)
  "%08X" % crc
end


text = "Ruby Programming"

crc = crc32_of_string(text)

puts "CRC32: #{crc}"


# run:
# 
# CRC32: 72938891
#

 



answered May 8 by avibootz
...