3

I receive an Int from my server which I’d like to explode in to an array of bit masks. So for example, if my server gives me the number 3, we get two values, a binary 1 and a binary 2.

How do I do this in Swift?

Adam Carter
  • 4,741
  • 5
  • 42
  • 103
  • Probably in this [](http://stackoverflow.com/questions/25267089/convert-a-two-byte-uint8-array-to-a-uint16-in-swift) you can find interest: let data= NSData(array) – GeekRiky Feb 08 '15 at 23:49
  • Does this answer your question? [How to convert a decimal number to binary in Swift?](https://stackoverflow.com/questions/26181221/how-to-convert-a-decimal-number-to-binary-in-swift) – hariszaman May 08 '20 at 01:41

4 Answers4

6

You could use:

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

prints "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)

prints "4f"

Jeremy Pope
  • 3,342
  • 1
  • 16
  • 17
4

I am not aware of any nice built-in way, but you could use this:

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

var b = a.map { Int(i & (1 << $0)) }
// b = [1, 2, 0, 0, 0, 0, 0, 0]
MirekE
  • 11,515
  • 5
  • 35
  • 28
1

Here is a straightforward implementation:

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]"
vacawama
  • 150,663
  • 30
  • 266
  • 294
1
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]

Reverse the result too, if you need it.