Skip to content

Instantly share code, notes, and snippets.

@VojtaStavik
Created April 5, 2017 19:17
Show Gist options
  • Save VojtaStavik/35ad31e37c3a34ee930685f9dbc36bf1 to your computer and use it in GitHub Desktop.
Save VojtaStavik/35ad31e37c3a34ee930685f9dbc36bf1 to your computer and use it in GitHub Desktop.
func calculateHammingDistance(x: Int, y: Int) -> Int {
// Step 1: Find different bits
let signedDifferentBits = x ^ y
// We bitcast Int to UInt to allow the algorithm work correctly also for negative numbers.
var differentBits: UInt = unsafeBitCast(signedDifferentBits, to: UInt.self)
// Step 2: Count them
var counter = 0
// Until there are some bits set to '1' in differentBits.
while differentBits > 0 {
// Mask differentBits with number 1 aka 00000001.
// By doing this, we set all bits of differentBits
// but the last one to zero.
let maskedBits = differentBits & 1
// If the last bit is not zero,
if maskedBits != 0 {
// increment the counter.
counter += 1
}
// Shift bits in differentBits to the right.
differentBits = differentBits >> 1
}
// We're done, return the number of 1s we've found.
return counter
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment