Swift 打印二进制
2016-01-07 本文已影响569人
公爵海恩庭斯
关于 Swift 二进制、八进制、十六进制的表示方法不再赘述,参考苹果官方手册 The Swift Programming Language。苦于百度找不到打印方法,最后还是 StackOverFlow 拯救了我。
示例代码:
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)
}