2020年1月

Swift 打印二进制

示例代码:

let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // 按位取反
let stringOfInvertedBits = String(invertedBits, radix: 2) // 转化为字符串
print(stringOfInvertedBits) // 输出结果为 11110000
let stringOfInvertedBits = String(invertedBits, radix: 2)
相当于
let stringOfInvertedBits = String(invertedBits, radix: 2, uppercase: false)

函数定义:

extension String {
    /// Create an instance representing `v` in base 10.
    public init<T : _SignedIntegerType>(_ v: T)
    /// Create an instance representing `v` in base 10.
    public init<T : UnsignedIntegerType>(_ v: T)
    /// Create an instance representing `v` in the given `radix` (base).
    ///
    /// Numerals greater than 9 are represented as roman letters,
    /// starting with `a` if `uppercase` is `false` or `A` otherwise.
    public init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
    /// Create an instance representing `v` in the given `radix` (base).
    ///
    /// Numerals greater than 9 are represented as roman letters,
    /// starting with `a` if `uppercase` is `false` or `A` otherwise.
    public init<T : UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
}

Link: