Skip to content

Instantly share code, notes, and snippets.

@arturopala
Last active November 29, 2017 16:37
Show Gist options
  • Save arturopala/349f3ee0ec9f69d0d725fb45b9d71a82 to your computer and use it in GitHub Desktop.
Save arturopala/349f3ee0ec9f69d0d725fb45b9d71a82 to your computer and use it in GitHub Desktop.
import java.nio.charset.Charset
import org.scalatest.{Matchers, WordSpec}
import scala.util.Random
class CRC5Spec extends WordSpec with Matchers {
/**
* Implements a "normal" MSB-first byte-width CRC5 function using a lookup table.
* See the <a href="http://reveng.sourceforge.net/crc-catalogue/">Catalogue of
* parametrised CRC algorithms</a> for more information on these algorithms and
* others.
*/
object CRC5 {
/* Params for CRC-5/EPC */
val bitWidth = 5
val poly = 0x09
val initial = 0x09
val xorOut = 0
val table: Seq[Int] = {
val widthMask = (1 << bitWidth) - 1
val shpoly = poly << (8 - bitWidth)
for (i <- 0 until 256) yield {
var crc = i
for (_ <- 0 until 8) {
crc = if ((crc & 0x80) != 0) (crc << 1) ^ shpoly else crc << 1
}
(crc >> (8 - bitWidth)) & widthMask
}
}
val ASCII = Charset.forName("ASCII")
def calculate(string: String): Int = calculate(string.getBytes())
def calculate(input: Array[Byte]): Int = {
val start = 0
val length = input.length
var crc = initial ^ xorOut
for (i <- 0 until length) {
crc = table((crc << (8 - bitWidth)) ^ (input(start + i) & 0xff)) & 0xff
}
crc ^ xorOut
}
}
"CRC5" should {
"calculate checksum" in {
CRC5.calculate("AB") shouldBe CRC5.calculate("AB")
CRC5.calculate("AB") should not be CRC5.calculate("BA")
CRC5.calculate("ABC") should not be CRC5.calculate("ACB")
CRC5.calculate("ABC") should not be CRC5.calculate("BAC")
CRC5.calculate("ABC") should not be CRC5.calculate("CBA")
CRC5.calculate("ABCDEFGHIJKLMNOPRSTUWXYZ0123456789") shouldBe CRC5.calculate("ABCDEFGHIJKLMNOPRSTUWXYZ0123456789")
CRC5.calculate("ABCDEFGHIJKLMNOPRSTUWXYZ0123456789") should not be CRC5.calculate("ABCDEFGHIJKLMNPORSTUWXYZ0123456789")
CRC5.calculate("ABCDEFGHIJKLMNOPRSTUWXYZ0123456789") should not be CRC5.calculate("ABCDEFGHIJKLMNOORSTUWXYZ0123456789")
CRC5.calculate("ABCDEFGHIJKLMNOPRSTUWXYZ0123456789") should not be CRC5.calculate("aBCDEFGHIJKLMNOPRSTUWXYZ0123456789")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment