How to calculate the CRC32 of a string in Scala

1 Answer

0 votes
import java.util.zip.CRC32
import java.nio.charset.StandardCharsets

object Main {

  /**
    * Calculates the CRC32 checksum of a string.
    *
    * @param input The string to hash.
    * @return The CRC32 value as an 8‑character uppercase hex string.
    */
  def crc32OfString(input: String): String = {
    // Create a CRC32 instance (from Java standard library)
    val crc = new CRC32()

    // Convert the string to UTF‑8 bytes
    val bytes = input.getBytes(StandardCharsets.UTF_8)

    // Feed the bytes into the CRC32 calculator
    crc.update(bytes)

    // Get the computed CRC32 value (stored as a long)
    val value = crc.getValue

    // Format as 8‑digit uppercase hexadecimal (standard CRC32 format)
    f"$value%08X"
  }

  def main(args: Array[String]): Unit = {
    val text = "Scala Programming"

    // Compute the CRC32 of the string
    val crc = crc32OfString(text)

    println(s"CRC32: $crc")
  }
}



/*
run:

CRC32: FABB9B1D

*/

 



answered May 8 by avibootz
...