Last active
March 9, 2021 17:32
-
-
Save SteveTrewick/fe8bf2da5151ebb5a6318143534e9392 to your computer and use it in GitHub Desktop.
Reverse the bits of an integer in Swift
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
func reverse <T: FixedWidthInteger> ( word: T ) -> T { | |
var word = word | |
var rev : T = 0 | |
for _ in (0..<word.bitWidth) { | |
rev = (rev << 1) + (word & 0b1) | |
word >>= 1 | |
} | |
return rev | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment