Swift.从整数中获取二进制字符串

vxbzzdmp  于 2022-11-21  发布在  Swift
关注(0)|答案(4)|浏览(103)

我有一个二进制数0000010,它被表示为一个整型数组。
let number = Int32([0, 0, 0, 0, 0, 1, 0].reduce(0, combine: {$0*2 + $1}))//数量=2
但当我想通过逆运算得到String时:
let binaryString = String(2, radix: 2)//二进制字符串=“10”
如果基数为0,那么基数会削减一些位,如何返回5个零?

wz3gfoph

wz3gfoph1#

let binaryString = String(2, radix: 2)
let other = String(count: 8 - binaryString.characters.count, repeatedValue: Character("0")) + binaryString
i34xakig

i34xakig2#

String构造函数在转换之前**无法知道Integer有多少个0位,你必须自己处理。
顺便说一下,Int也有radix构造函数,用于将字符串转换为Int:

Int("0000010", radix: 2) // Returns 2
ecbunoof

ecbunoof3#

"雨燕5"

var binaryString = String(2, radix: 2)
binaryString = String(repeating: "0", count: 8 - binaryString.count) + binaryString
ttygqcqt

ttygqcqt4#

FixedWidthInteger协议的文档提供了一个表示数字二进制的有趣示例:

extension FixedWidthInteger {
    var binaryString: String {
        var result: [String] = []
        for i in 0..<(Self.bitWidth / 8) {
            let byte = UInt8(truncatingIfNeeded: self >> (i * 8))
            let byteString = String(byte, radix: 2)
            let padding = String(repeating: "0",
                                 count: 8 - byteString.count)
            result.append(padding + byteString)
        }
        return "0b" + result.reversed().joined(separator: "_")
    }
}

print(Int16.max.binaryString) // Prints "0b01111111_11111111"
print((101 as UInt8).binaryString) // Prints "0b11001001"

相关问题