Swift将整数转换为2个字符的十六进制字符串

Ian*_*lay 6 swift xcode6 swift2

我想从一个整数中获取一个两个字符的十六进制值:

let hex = String(format:"%2X", 0)
print ("hex = \(hex)")
Run Code Online (Sandbox Code Playgroud)

十六进制="0"

如何格式化String以产生总共2个字符,在这种情况下我想要

十六进制="00"

aya*_*aio 15

您可以在格式化程序字符串之前添加填充0:

let hex = String(format:"%02X", 0)
Run Code Online (Sandbox Code Playgroud)

结果:

let hex = String(format:"%02X", 0) // 00
let hex = String(format:"%02X", 15) // 0F
let hex = String(format:"%02X", 16) // 10
Run Code Online (Sandbox Code Playgroud)

  • @IanClay:这个`String`方法实际上是从相应的`NSString`方法桥接的.NSString文档有[String Format specifiers]的链接(https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265 )这反过来又链接到[IEEE printf规范](http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html),这是最终的参考.容易,不是吗? (3认同)