ios 如何在 Swift 中将 Int 转换为 Hex 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24229505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:54:43  来源:igfitidea点击:

How to convert an Int to Hex String in Swift

iosstringhexswift

提问by boscarol

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

在 Obj-C 中,我曾经将一个无符号整数 n 转换为一个十六进制字符串

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

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

我尝试了很长时间将其翻译成 Swift 语言,但没有成功。

回答by vacawama

You can now do:

你现在可以这样做:

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
0E is the hexadecimal representation of 14

Note: The 2in this example is the field widthand represents the minimumlength desired. The 0tells it to pad the result with leading 0's if necessary. (Without the 0, the result would be padded with leading spaces). 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.

注意:2本例中的 是字段宽度,表示所需的最小长度。在0它告诉垫与领先的结果0的如果需要的话。(没有0,结果将用前导空格填充)。当然,如果结果大于两个字符,则字段长度不会被裁剪为宽度2;它将扩展到显示完整结果所需的任何长度。

This only works if you have Foundationimported (this includes the import of Cocoaor UIKit). This isn't a problem if you're doing iOSor macOSprogramming.

这仅在您已Foundation导入(这包括Cocoa或的导入UIKit)时才有效。如果您在进行iOSmacOS编程,这不是问题。

Use uppercase Xif you want A...Fand lowercase xif you want a...f:

使用大写X,如果你想A...F和小写字母x,如果你想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:

如果要打印大于 的整数值UInt32.max,请将llel-el,而不是11)添加到格式字符串中:

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


Original Answer

原答案

You can still use NSStringto do this. The format is:

您仍然可以使用它NSString来执行此操作。格式为:

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

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

这使得st一个NSString,所以接下来的事情想+=不工作。如果你希望能够追加到带有字符串+=化妆stString这样的:

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"

回答by Rich

In Swift there is a specific initmethod on Stringfor exactly this:

在 Swift 中有一个特定的init方法来String解决这个问题:

let hex = String(0xF, radix: 16, uppercase: false)
println("hex=\(hex)") // Output: f

回答by Imanou Petit

With Swift 5, according to your needs, you may choose one of the three following methods in order to solve your problem.

使用 Swift 5,您可以根据需要,选择以下三种方法之一来解决您的问题。



#1. Using String's init(_:radix:uppercase:)initializer

#1. 使用 Stringinit(_:radix:uppercase:)初始化程序

Swift Stringhas a init(_:radix:uppercase:)initializer with the following declaration:

SwiftString有一个init(_:radix:uppercase:)初始化程序,声明如下:

init<T>(_ value: T, radix: Int = 10, uppercase: Bool = false) where T : BinaryInteger

Creates a string representing the given value in base 10, or some other specified base.

创建一个字符串,表示以 10 为基数的给定值,或其他指定的基数。

The Playground code below shows how to create a Stringinstance that represents an integer value in hexadecimal format by using init(_:radix:uppercase:)and without having to import Foundation:

下面的 Playground 代码显示了如何String通过使用init(_:radix:uppercase:)和无需导入来创建一个表示十六进制格式的整数值的实例Foundation

let string1 = String(2, radix: 16)
print(string1) // prints: "2"

let string2 = String(211, radix: 16)
print(string2) // prints: "d3"

let string3 = String(211, radix: 16, uppercase: true)
print(string3) // prints: "D3"


#2. Using String's init(format:?_:?)initializer

#2. 使用Stringinit(format:?_:?)初始化程序

Foundationprovides Stringa init(format:?_:?)initializer. init(format:?_:?)has the following declaration:

Foundation提供String一个init(format:?_:?)初始化程序。init(format:?_:?)有以下声明:

init(format: String, _ arguments: CVarArg...)

Returns a Stringobject initialized by using a given format string as a template into which the remaining argument values are substituted.

返回String使用给定格式字符串作为模板初始化的对象,其余参数值将被替换到该模板中。

The Apple's String Programming Guidegives a list of the format specifiers that are supported by Stringand NSString. Among those format specifiers, %Xhas the following description:

Apple 的String Programming Guide提供了String和支持的格式说明符列表NSString。在这些格式说明符中,%X有以下描述

Unsigned 32-bit integer (unsigned int), printed in hexadecimal using the digits 0–9 and uppercase A–F.

无符号 32 位整数 ( unsigned int),使用数字 0–9 和大写 A–F 以十六进制打印。

The Playground code below shows how to create a Stringinstance that represents an integer value in hexadecimal format with init(format:?_:?):

下面的 Playground 代码显示了如何创建一个String表示十六进制格式的整数值的实例init(format:?_:?)

import Foundation

let string1 = String(format:"%X", 2)
print(string1) // prints: "2"

let string2 = String(format:"%02X", 1)
print(string2) // prints: "01"

let string3 = String(format:"%02X", 211)
print(string3) // prints: "D3"

let string4 = String(format: "%02X, %02X, %02X", 12, 121, 255)
print(string4) // prints: "0C, 79, FF"


#3. Using String's init(format:?arguments:?)initializer

#3. 使用Stringinit(format:?arguments:?)初始化程序

Foundationprovides Stringa init(format:?arguments:?)initializer. init(format:?arguments:?)has the following declaration:

Foundation提供String一个init(format:?arguments:?)初始化程序。init(format:?arguments:?)有以下声明:

init(format: String, arguments: [CVarArg])

Returns a Stringobject initialized by using a given format string as a template into which the remaining argument values are substituted according to the user's default locale.

返回String通过使用给定格式字符串作为模板初始化的对象,根据用户的默认语言环境将其余参数值替换到其中。

The Playground code below shows how to create a Stringinstance that represents an integer value in hexadecimal format with init(format:?arguments:?):

下面的 Playground 代码显示了如何创建一个String表示十六进制格式的整数值的实例init(format:?arguments:?)

import Foundation

let string1 = String(format:"%X", arguments: [2])
print(string1) // prints: "2"

let string2 = String(format:"%02X", arguments: [1])
print(string2) // prints: "01"

let string3 = String(format:"%02X",  arguments: [211])
print(string3) // prints: "D3"

let string4 = String(format: "%02X, %02X, %02X",  arguments: [12, 121, 255])
print(string4) // prints: "0C, 79, FF"

回答by Goodtime

To use

使用

let string2 = String(format:"%02X", 1)
print(string2) // prints: "01"

In Swift3 import foundation is not required, At least not in a Project. String should have all the functionality as NSString.

在 Swift3 中不需要导入基础,至少在项目中不需要。String 应该具有 NSString 的所有功能。

回答by MikeJ

Answers above work fine for values in the range of a 32 bit Int, but values over this won't work as the value will roll over.

上面的答案适用于 32 位 Int 范围内的值,但超过此值的值将不起作用,因为该值将翻转。

You need to use the length modifierfor values greater than a 32bit Int

您需要对大于 32 位 Int 的值使用长度修饰符

%x = Unsigned 32-bit integer (unsigned int)

%x = 无符号 32 位整数(无符号整数)

ll = Length modifiers specifying that a following d, o, u, x, or X conversion specifier applies to a long long or unsigned long long argument.

ll = 长度修饰符,指定后面的 d、o、u、x 或 X 转换说明符适用于 long long 或 unsigned long long 参数。

let hexString = String(format:"%llX", decimalValue)