【问题标题】:Leading Binary Zeros in Swift [duplicate]Swift 中的前导二进制零 [重复]
【发布时间】:2016-12-06 03:50:00
【问题描述】:

我正在接受一个十六进制值并将其转换为二进制数,但是它没有打印出前导零。我知道 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
 }
}

非常感谢任何帮助。

【问题讨论】:

  • 链接到的“重复”具有 Swift 1、2 和 3 的代码。

标签: swift swift3


【解决方案1】:

另一种创建固定长度(具有前导 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"

【讨论】:

  • 为什么Any 作为返回类型而不是String
  • @MartinR,这只是一个错误。也许我已经接受了一些 Xcode 建议,但尚未完成。
猜你喜欢
  • 2011-08-31
  • 2015-02-22
  • 1970-01-01
  • 2013-05-10
  • 1970-01-01
  • 2013-05-31
  • 1970-01-01
  • 2013-03-03
相关资源
最近更新 更多