How can I convert Int to UInt8 in Swift? Example. I want to convert number 22 to 0b00010110
var decimal = 22 var binary:UInt8 = ??? //What should I write here?
Overview. The BinaryInteger protocol is the basis for all the integer types provided by the standard library. All of the standard library's integer types, such as Int and UInt32 , conform to BinaryInteger .
The binary equivalent of 15 is 1111. That means, the decimal number 15 can be written in the binary system as 1111.
A binary integer variable—also called a 0/1 variable—is a special case of an integer variable that is required to be either zero or one. It's often used as a switch to model Yes/No decisions.
For example, if your birthday is on June 11, 2013, it would be written as 6/11/13. 2. Convert the birthday date to binary format. Using our same example from above, 6/11/13 translated into binary code would be: 110/1011/1101.
You can convert the decimal value to a human-readable binary representation using the String
initializer that takes a radix
parameter:
let num = 22 let str = String(num, radix: 2) print(str) // prints "10110"
If you wanted to, you could also pad it with any number of zeroes pretty easily as well:
Swift 5
func pad(string : String, toSize: Int) -> String { var padded = string for _ in 0..<(toSize - string.count) { padded = "0" + padded } return padded } let num = 22 let str = String(num, radix: 2) print(str) // 10110 pad(string: str, toSize: 8) // 00010110
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With