2016-12-06 43 views
2

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

@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 
} 
} 

任何帮助,非常感谢。

+0

链接到的“重复”具有代码夫特1,2,和3。 –

回答

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" 
+0

为什么'Any'作为返回键入而不是'String'? –

+0

@MartinR,这只是一个错误。也许我还没有完成就接受了一些Xcode的建议。 – OOPer

相关问题