How to convert a decimal number to binary in Swift

2020-01-29 04:05发布

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?

标签: swift
13条回答
来,给爷笑一个
2楼-- · 2020-01-29 04:28

I agree with the others, Although the for-loop seems redundant for repeating a character.
we can simply go with the following String initialiser:

init(count count: Int, repeatedValue c: Character)

usage example:

let string = String(count: 5, repeatedValue: char)

Here is a full example:

let someBits: UInt8 = 0b00001110
let str = String(someBits, radix:2) //binary base
let padd = String(count: (8 - str.characters.count), repeatedValue: Character("0")) //repeat a character
print(padd + str)
查看更多
登录 后发表回答