Skip to content

Instantly share code, notes, and snippets.

@SteveTrewick
Last active March 9, 2021 17:32
Show Gist options
  • Save SteveTrewick/fe8bf2da5151ebb5a6318143534e9392 to your computer and use it in GitHub Desktop.
Save SteveTrewick/fe8bf2da5151ebb5a6318143534e9392 to your computer and use it in GitHub Desktop.
Reverse the bits of an integer in Swift
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