Richard Searle


The Fletcher checksum and scodec

06 Sep 2014

The Fletcher checksum could be computed using the scodec infrastructure as follows:

object FletcherChecksum {

  def apply(bv:BitVector): BitVector = {
    val csum = bv.toByteArray.foldLeft((0, 0)) { (p, b) =>
        val lsb = (p._2 + (0xff & b)) % 255
        ((p._1 + lsb) % 255, lsb)
    bv ++BitVector(csum._1.asInstanceOf[Byte], csum._2.asInstanceOf[Byte])

Note the checksum is appended to the input BitVector.

With a test

def wikipedia {
   assertEquals(BitVector(0x01, 0x02, 0x04, 0x03), 
      FletcherChecksum(BitVector(0x01, 0x02)))

This design is not consistent with the scodec cryptographic signing functionality. Unfortunately that code is built around the Java security API and the core class is not appropriate for very much simpler checksum functionality.