在Obj-C中,我曾使用以下命令将无符号整数n转换为十六进制字符串:
NSString *st = [NSString stringWithFormat:@"%2X", n];
我花了很长时间尝试将其翻译成Swift语言,但未成功。
您现在可以执行以下操作:
let n = 14
var st = String(format:"%02X", n)
st += " is the hexadecimal representation of \(n)"
print(st)
0E is the hexadecimal representation of 14
注意:2
在此示例中,是字段宽度,代表所需的最小长度。在0
它告诉垫与领先的结果0
的如果需要的话。(如果没有0
,结果将用前导空格填充)。当然,如果结果大于两个字符,则字段长度将不会被剪裁为2
;它将扩展到显示完整结果所需的任何长度。
仅在您Foundation
导入后才有效(包括Cocoa
或的导入UIKit
)。如果您正在执行iOS或macOS编程,这不是问题。
使用大写X
,如果你想A...F
和小写字母x
,如果你想a...f
:
String(format: "%x %X", 64206, 64206) // "face FACE"
如果要打印大于的整数值,请在格式字符串中UInt32.max
添加ll
(el-el,而不是11):
let n = UInt64.max
print(String(format: "%llX is hexadecimal for \(n)", n))
FFFFFFFFFFFFFFFF is hexadecimal for 18446744073709551615
原始答案
您仍然可以使用NSString
此功能。格式为:
var st = NSString(format:"%2X", n)
这会st
造成NSString
,因此类似之类的东西+=
将不起作用。如果你希望能够追加到带有字符串+=
化妆st
成String
这样的:
var st = NSString(format:"%2X", n) as String
要么
var st = String(NSString(format:"%2X", n))
要么
var st: String = NSString(format:"%2X", n)
然后,您可以执行以下操作:
let n = 123
var st = NSString(format:"%2X", n) as String
st += " is the hexadecimal representation of \(n)"
// "7B is the hexadecimal representation of 123"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句