How to calculate the CRC32 of a string in Kotlin

1 Answer

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

// Calculates the CRC32 checksum of a string.
// Returns an 8‑character uppercase hexadecimal string.
fun crc32OfString(input: String): String {
    // Create a CRC32 instance (from Java standard library)
    val crc = CRC32()

    // Convert the string to UTF‑8 bytes
    val bytes = input.toByteArray(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.value

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

fun main() {
    val text = "Kotlin Programming"

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

    println("CRC32: $crc")
}



/*
run:

CRC32: FBFC6A8A

*/

 



answered May 8 by avibootz
...