Skip to content

Instantly share code, notes, and snippets.

@melkael melkael/hamming.go
Created Feb 1, 2019

Embed
What would you like to do?
func hexToBinary(hexnum string) string {
if hexnum == "0" {
return "0000"
} else if hexnum == "1" {
return "0001"
} else if hexnum == "2" {
return "0010"
} else if hexnum == "3" {
return "0011"
} else if hexnum == "4" {
return "0100"
} else if hexnum == "5" {
return "0101"
} else if hexnum == "6" {
return "0110"
} else if hexnum == "7" {
return "0111"
} else if hexnum == "8" {
return "1000"
} else if hexnum == "9" {
return "1001"
} else if hexnum == "a" || hexnum == "A" {
return "1010"
} else if hexnum == "b" || hexnum == "B" {
return "1011"
} else if hexnum == "c" || hexnum == "C" {
return "1100"
} else if hexnum == "d" || hexnum == "D" {
return "1101"
} else if hexnum == "e" || hexnum == "E" {
return "1110"
} else {
return "1111"
}
}
// THIS FUNCTION TAKES HEX STRING REPRESENTATIONs OF THE TWO STRINGS AS ARGUMENTS
func hamming(s1 string, s2 string) int {
//hex1 := fmt.Sprintf("%x", s1)
//hex2 := fmt.Sprintf("%x", s2)
bytes_s1, _ := hex.DecodeString(s1)
bytes_s2, _ := hex.DecodeString(s2)
bytes_str1 := fmt.Sprintf("%x", bytes_s1)
bytes_str1 = strings.Join(strings.Fields(bytes_str1), "")
bytes_str2 := fmt.Sprintf("%x", bytes_s2)
bytes_str2 = strings.Join(strings.Fields(bytes_str2), "")
bin_str1 := ""
bin_str2 := ""
for _, char := range bytes_str1 {
bin_str1 += hexToBinary(fmt.Sprintf("%c", char))
}
for _, char := range bytes_str2 {
bin_str2 += hexToBinary(fmt.Sprintf("%c", char))
}
distance := 0
for i := 0; i < len(bin_str1); i++ {
if bin_str1[i] != bin_str2[i] {
distance++
}
}
return distance
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.