Last active
June 2, 2020 19:19
-
-
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
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 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