Skip to content

Instantly share code, notes, and snippets.

@iboy
Last active June 2, 2020 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iboy/6a7ed49b1d972bd895fdc7f97533aecd to your computer and use it in GitHub Desktop.
Save iboy/6a7ed49b1d972bd895fdc7f97533aecd to your computer and use it in GitHub Desktop.
A generic swift function to print the "binary string" of any `FixedWidthInteger`. #swift5 #binary
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