且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift中将Int转换为十六进制字符串

更新时间:2022-11-18 18:13:57

您现在可以这样做:

  n = 14 
var st = String(格式:%2X,n)
st + =是\(n)的十六进制表示
print (st)




  0E是14 


的十六进制表示注意: 2 在这个例子中是字段宽度并且表示所需的最小长度长度。如有必要,结果将会填入前导 0 的结果。当然,如果结果大于两个字符,则字段长度将不会被裁剪为宽度2;它会扩展到显示完整结果所需的任何长度。



只有当 Foundation 导入时才有效(这包括导入 Cocoa UIKit )。如果您正在执行 iOS OS X 编程,则这不是问题。

使用大写字母 A ... F 和小写 x if X if你想要 a ... f

 字符串(格式: %x%X,64206,64206)//face face

如果您想打印整数值大于 UInt32.max ,添加 ll el-el ,而不是

  let n = UInt64.max 
print(String em> eleven ) (格式:%llX是\(n)的十六进制,n))




  FFFFFFFFFFFFFFFF是十六进制的18446744073709551615 


原始答案

您仍然可以使用 NSString 来做到这一点。格式为:

  var st = NSString(格式:%2X,n)
$

这使得 st an NSString ,那么诸如 + = 之类的东西不起作用。如果您希望能够将 + = 使 st 添加到字符串中,字符串像这样:

  var st = NSString(format:%2X,n)as字符串

  var st = String(NSString(format:%2X,n))

  var st:String = NSString(format:%2X,n)
$ c



然后你可以这样做:

pre $ code $>让n = 123
var st = NSString(格式:%2X,n)作为字符串
st + =是\(n)的十六进制表示
// 7B是123


的十六进制表示

In Obj-C I used to convert an unsigned integer n to a hex string with

 NSString *st = [NSString stringWithFormat:@"%2X", n];

I tried for a long time to translate this into Swift language, but unsuccessfully.

You can now do:

let n = 14
var st = String(format:"%2X", n)
st += " is the hexadecimal representation of \(n)"
print(st)

0E is the hexadecimal representation of 14

Note: The 2 in this example is the field width and represents the minimum length desired. The result will be padded with leading 0's if necessary. Of course, if the result is larger than two characters, the field length will not be clipped to a width of 2; it will expand to whatever length is necessary to display the full result.

This only works if you have Foundation imported (this includes the import of Cocoa or UIKit). This isn't a problem if you're doing iOS or OS X programming.

Use uppercase X if you want A...F and lowercase x if you want a...f:

String(format: "%x %X", 64206, 64206)  // "face FACE"

If you want to print integer values larger than UInt32.max, add ll (el-el, not eleven) to the format string:

let n = UInt64.max
print(String(format: "%llX is hexadecimal for \(n)", n))

FFFFFFFFFFFFFFFF is hexadecimal for 18446744073709551615


Original Answer

You can still use NSString to do this. The format is:

var st = NSString(format:"%2X", n)

This makes st an NSString, so then things like += do not work. If you want to be able to append to the string with += make st into a String like this:

var st = NSString(format:"%2X", n) as String

or

var st = String(NSString(format:"%2X", n))

or

var st: String = NSString(format:"%2X", n)

Then you can do:

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"