Swift中领先的二进制零

时间:2016-12-06 03:50:01

标签: swift swift3

我接受十六进制值并将其转换为二进制数,但是,它不会打印出前导零。我知道swift没有像C这样的内置能力。我想知道是否有办法打印出任何前导零,当我知道最大的二进制数将是16个字符。我有一些代码,通过取十六进制数,将其转换为十进制数,然后转换为二进制数来为我运行。

@IBAction func HextoBinary(_ sender: Any)
{
//Removes all white space and recognizes only text
let origHex = textView.text.trimmingCharacters(in: .whitespacesAndNewlines)
if let hexNumb_int = Int(origHex, radix:16)
 {
   let decNumb_str = String(hexNumb_int, radix:2)
   textView.text = decNumb_str
 }
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

创建固定长度(具有前导0的)二进制表示的另一种方法:

extension UnsignedInteger {
    func toFixedBinaryString(_ bits: Int = MemoryLayout<Self>.size*8) -> String {
        let uBits = UIntMax(bits)
        return (0..<uBits)
            .map { self.toUIntMax() & (1<<(uBits-1-$0)) != 0 ? "1" : "0" }
            .joined()
    }
}
extension SignedInteger {
    func toFixedBinaryString(_ bits: Int = MemoryLayout<Self>.size*8) -> String {
        return UIntMax(bitPattern: self.toIntMax()).toFixedBinaryString(bits)
    }
}

let b: UInt16 = 0b0001_1101_0000_0101
b.toFixedBinaryString(16) //=>"0001110100000101"
b.toFixedBinaryString()   //=>"0001110100000101"

let n: Int = 0x0123_CDEF
n.toFixedBinaryString(32) //=>"00000001001000111100110111101111"
n.toFixedBinaryString()   //=>"0000000000000000000000000000000000000001001000111100110111101111"