Created
July 7, 2013 15:30
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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