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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.