如何在Swift中将十进制数转换为二进制数? [英] How to convert a decimal number to binary in Swift?

查看:41
本文介绍了如何在Swift中将十进制数转换为二进制数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 中将 Int 转换为 UInt8?例子.我想将数字 22 转换为 0b00010110

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?

推荐答案

您可以使用 String 初始化程序将十进制值转换为人类可读的二进制表示radix 参数:

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

这篇关于如何在Swift中将十进制数转换为二进制数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆