Skip to content

Instantly share code, notes, and snippets.

@rjstelling
Created May 24, 2019 08:33
Show Gist options
  • Save rjstelling/3be83e4b5dbdb8b6278e324780938400 to your computer and use it in GitHub Desktop.
Save rjstelling/3be83e4b5dbdb8b6278e324780938400 to your computer and use it in GitHub Desktop.
A generic function to print the "binary string" of any `FixedWidthInteger`.
func print<T: FixedWidthInteger>(asBinary val: T) {
let bitCount = MemoryLayout<T>.size * 8
let binaryStr = String(val, radix: 2)
let zeroPadding = String(repeating: "0", count: bitCount - binaryStr.count)
print("0b\(zeroPadding)\(binaryStr)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment