如何在Swift中将Int转换为UInt8?例。我想将数字22转换为0b00010110
var decimal = 22 var binary:UInt8 = ??? //What should I write here?
您可以使用带有参数的初始化程序将十进制值转换为人类可读的二进制 表示形式 :String``radix
String``radix
let num = 22 let str = String(num, radix: 2) print(str) // prints "10110"
如果您愿意,也可以很容易地用任意数量的零填充它:
斯威夫特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