A Kotlin Adler-32 checksum algorithm

As a short post today, here’s an example of a Kotlin implementation of the Adler-32 checksum algorithm:

fun main(args: Array<String>) {
    val sum = adler32sum("Wikipedia")
    println("checksum (int) = $sum")

    val hexString = Integer.toHexString(sum)
    println("checksum (hex) = $hexString")
}

fun adler32sum(s: String): Int {
    val MOD_ADLER = 65521
    var a = 1
    var b = 0

    val byteArray = s.toByteArray()
    for (byte in byteArray) {
        a = (byte + a) % MOD_ADLER
        b = (b + a) % MOD_ADLER
    }

    // note: Int is 32 bits, which this requires
    return b * 65536 + a   // or (b << 16) + a
}

I already wrote about this in my Scala Adler-32 checksum algorthim tutorial, so please read that post for more information on the algorithm.