How to convert a decimal number to binary in Swift

2020-01-29 04:05发布

How can I convert Int to UInt8 in Swift? Example. I want to convert number 22 to 0b00010110

var decimal = 22
var binary:UInt8 = ??? //What should I write here?

标签: swift
13条回答
Luminary・发光体
2楼-- · 2020-01-29 04:06

You can convert the decimal value to a human-readable binary representation using the String initializer that takes a radix parameter:

let num = 22
let str = String(num, radix: 2)
print(str) // prints "10110"

If you wanted to, you could also pad it with any number of zeroes pretty easily as well:

func pad(string : String, toSize: Int) -> String {
  var padded = string
  for _ in 0..<(toSize - string.characters.count) {
    padded = "0" + padded
  }
    return padded
}

let num = 22
let str = String(num, radix: 2)
print(str) // 10110
pad(string: str, toSize: 8)  // 00010110
查看更多
甜甜的少女心
3楼-- · 2020-01-29 04:06

There is no difference between binary and decimal numeral systems, when you're working with variables until you want to visualize them or if you want to convert types which can hold different ammount of bits.

In your case is enough to write

var decimal = 22
var binary = UInt8(decimal)

But this will crash (overflow happens) if decimal will hold a value more than 255, because it is maximum value which UInt8 can hold.

Depending on what you want to achieve you can write

var decimal = 261 // 0b100000101
var binary = UInt8(truncatingBitPattern: decimal) // 0b00000101

You'll get 0 as a result, because this initializer will truncate less significant bits.

Second option is

var decimal = 256  // 0b100000000
var binary = UInt8(exactly: decimal) // nil

This initializer returns nil result instead of crashing, if overflow happens.

P.S. If you want to see binary string representation use

String(decimal, radix: 2)
String(binary, radix: 2)
查看更多
Explosion°爆炸
4楼-- · 2020-01-29 04:08

Went through a lot of answers on this post but I wonder why haven't anyone mentioned the API leadingZeroBitCount on FixedWidthInteger

This returns the number of zeros in specific UInt eg:

UInt(4).leadingZeroBitCount //61

UInt16(4).leadingZeroBitCount //13

Swift Version

4.1

USAGE

let strFive = String.binaryRepresentation(of: UInt8(5))
print(strFive) // Prints: 00000101 

UNDER THE HOOD

extension String {

    static func binaryRepresentation<F: FixedWidthInteger>(of val: F) -> String {

        let binaryString = String(val, radix: 2)

        if val.leadingZeroBitCount > 0 {
            return String(repeating: "0", count: val.leadingZeroBitCount) + binaryString
        }

        return binaryString
    }
}
查看更多
该账号已被封号
5楼-- · 2020-01-29 04:09

I modified your version to Swift 2.0 count on strings and added a length check:

extension String {
 func pad(length: Int) -> String {
    let diff = length - self.characters.count
    if diff > 0 {
        var padded = self
        for _ in 0..<diff {
            padded = "0" + padded
        }
        return padded
    } else {
        return self
    }
 }
}
查看更多
欢心
6楼-- · 2020-01-29 04:11

Most answers here forget to account for 0, and outputs a representation there is too long.

Based on the answer by @karwag I present:

extension FixedWidthInteger {
    var binaryStringRepresentation: String {
        words.reduce(into: "") {
            $0.append(contentsOf: repeatElement("0", count: $1.leadingZeroBitCount))
            if $1 != 0 {
                $0.append(String($1, radix: 2))
            }
        }
    }
}
查看更多
Viruses.
7楼-- · 2020-01-29 04:16

I modified someone's version to swift 3.0 used the correct initializer for creating a string with repeated values

extension String {
    func pad(with character: String, toLength length: Int) -> String {
        let padCount = length - self.characters.count
        guard padCount > 0 else { return self }

        return String(repeating: character, count: padCount) + self
    }
}

String(37, radix: 2).pad(with: "0", toLength: 8) // "00100101"
查看更多
登录 后发表回答