Skip to content

Instantly share code, notes, and snippets.

@nuclearace
Created November 21, 2019 14:14
Show Gist options
  • Select an option

  • Save nuclearace/b275c30f694b7c9162ca81b6ef01ece3 to your computer and use it in GitHub Desktop.

Select an option

Save nuclearace/b275c30f694b7c9162ca81b6ef01ece3 to your computer and use it in GitHub Desktop.
gray code
func grayEncode(_ i: Int) -> Int {
return (i >> 1) ^ i
}
func grayDecode(_ i: Int) -> Int {
switch i {
case 0:
return 0
case _:
return i ^ grayDecode(i >> 1)
}
}
for i in 0..<32 {
let iStr = String(i, radix: 2)
let encode = grayEncode(i)
let encodeStr = String(encode, radix: 2)
let decode = grayDecode(encode)
let decodeStr = String(decode, radix: 2)
print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment