Swift - 将Int转换为二进制表示

时间:2015-02-08 23:40:17

标签: swift bitmask

我从我的服务器收到一个Int,我想爆炸到一个位掩码数组。因此,例如,如果我的服务器给我3号,我们得到两个值,二进制1和二进制2。

我如何在Swift中执行此操作?

4 个答案:

答案 0 :(得分:4)

您可以使用:

let number = 3
//radix: 2 is binary, if you wanted hex you could do radix: 16
let str = String(number, radix: 2)
println(str)

打印“11”

let number = 79
//radix: 2 is binary, if you wanted hex you could do radix: 16
let str = String(number, radix: 16)
println(str)

打印“4f”

答案 1 :(得分:3)

我不知道任何好的内置方式,但你可以使用它:

var i = 3
let a = 0..<8

var b = a.map { Int(i & (1 << $0)) }
// b = [1, 2, 0, 0, 0, 0, 0, 0]

答案 2 :(得分:1)

这是一个简单的实现:

func intToMasks(var n: Int) -> [Int] {
    var masks = [Int]()
    var mask = 1
    while n > 0 {
        if n & mask > 0 {
            masks.append(mask)
            n -= mask
        }
        mask <<= 1
    }
    return masks
}

println(intToMasks(3))    // prints "[1,2]"
println(intToMasks(1000)) // prints "[8,32,64,128,256,512]"

答案 3 :(得分:0)

public extension UnsignedInteger {
  /// The digits that make up this number.
  /// - Parameter radix: The base the result will use.
  func digits(radix: Self = 10) -> [Self] {
    sequence(state: self) { quotient in
      guard quotient > 0
      else { return nil }

      let division = quotient.quotientAndRemainder(dividingBy: radix)
      quotient = division.quotient
      return division.remainder
    }
    .reversed()
  }
}
let digits = (6 as UInt).digits(radix: 0b10) // [1, 1, 0]
digits.reversed().enumerated().map { $1 << $0 } // [0, 2, 4]

如果需要,也可以反转结果。