2016-12-06 89 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

相關問題