Skip to content

Instantly share code, notes, and snippets.

@flakas
Created July 7, 2013 15:30
Show Gist options
  • Save flakas/5943814 to your computer and use it in GitHub Desktop.
Save flakas/5943814 to your computer and use it in GitHub Desktop.
Calculating Hamming distance of a byte array with number of bits set with Scala
object HammingDistance {
def main(args: Array[String]) = {
val b1 : Array[Byte] = Array(5, 7) // 0b00000101, 0b00000111
val b2 : Array[Byte] = Array(6, 8) // 0b00000110, 0b00001000
println(hammingDistance(b1, b2)) // Output: 6
}
// Calculate a sum of set bits of XOR'ed bytes
def hammingDistance(b1: Array[Byte], b2: Array[Byte]) = {
(b1.zip(b2).map((x: (Byte, Byte)) => numberOfBitsSet((x._1 ^ x._2).toByte))).sum
}
// 1 iteration for each bit, 8 total. Shift right and AND 1 to get i-th bit
def numberOfBitsSet(b: Byte) : Int = (0 to 7).map((i : Int) => (b >>> i) & 1).sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment