Created
November 21, 2019 14:14
-
-
Save nuclearace/b275c30f694b7c9162ca81b6ef01ece3 to your computer and use it in GitHub Desktop.
gray code
This file contains hidden or 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
| 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