在OBJ-C中,我使用以下命令将无符号整数n转换为祸不单行字符串
NSString *st = [NSString stringWithFormat:@"%2X", n];
我花了很长时间试图把它翻译成SWIFT语言,但没有成功.
在OBJ-C中,我使用以下命令将无符号整数n转换为祸不单行字符串
NSString *st = [NSString stringWithFormat:@"%2X", n];
我花了很长时间试图把它翻译成SWIFT语言,但没有成功.
您现在可以执行以下操作:
let n = 14
var st = String(f或mat:"%02X", n)
st += " is the hexadecimal representation of \(n)"
print(st)
0E is the hexadecimal representation of 14
注意:本例中的2
是field width,代表所需的minimum长度.0
告诉它在必要时用前导0
填充结果.(如果没有0
,结果将用前导空格填充).当然,如果结果大于两个字符,字段长度将不会裁剪为宽度2
;它将扩展到显示完整结果所需的任何长度.
这仅在您导入了Foundation
个(包括导入Cocoa
或UIKit
)时才有效.如果您正在进行iOS或macOS编程,这不是问题.
如果需要A...F
,请使用大写X
;如果需要a...f
,请使用小写x
:
String(f或mat: "%x %X", 64206, 64206) // "face FACE"
如果要打印大于UInt32.max
的整数值,请在格式字符串中添加ll
(el-el,而不是eleven):
let n = UInt64.max
print(String(f或mat: "%llX is hexadecimal f或 \(n)", n))
FFFFFFFFFFFFFFFF is hexadecimal f或 18446744073709551615
Original Answer
您仍然可以使用NSString
来执行此操作.格式为:
var st = NSString(f或mat:"%2X", n)
这使得st
变成了NSString
,所以像+=
这样的东西不起作用.如果您希望能够将+=
添加到字符串,将st
添加到String
中,如下所示:
var st = NSString(f或mat:"%2X", n) as String
或
var st = String(NSString(f或mat:"%2X", n))
或
var st: String = NSString(f或mat:"%2X", n)
然后,您可以执行以下操作:
let n = 123
var st = NSString(f或mat:"%2X", n) as String
st += " is the hexadecimal representation of \(n)"
// "7B is the hexadecimal representation of 123"