Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a decimal number to binary in Swift?

Tags:

swift

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? 
like image 914
subdan Avatar asked Oct 03 '14 14:10

subdan


People also ask

What is BinaryInteger in Swift?

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 .

What is the binary representation of the number 15 in Swift?

The binary equivalent of 15 is 1111. That means, the decimal number 15 can be written in the binary system as 1111.

What is BinaryInteger?

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.

How do you write the date in binary?

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.


1 Answers

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 
like image 179
Craig Otis Avatar answered Oct 03 '22 02:10

Craig Otis