简体   繁体   English

如何在Swift3中将ASCII转换为十六进制?

[英]How to convert ASCII to hex in Swift3?

I have converted the string "UK" into hex using code below. 我已使用以下代码将字符串“ UK”转换为十六进制。 How can I convert it to hex? 如何将其转换为十六进制?

    let str = auxText
    let bytes = str.utf8
    var buffer = [UInt8](bytes)
    buffer[0] = buffer[0] + UInt8(1)
    print("ascii value is",buffer)

In Swift 4, you can convert your ascii encoded string to data with 在Swift 4中,您可以将ASCII编码的string转换为

string.data(using: .ascii)

To convert the data to hex or decimal you can use the following extensions: 要将数据转换为十六进制或十进制,可以使用以下扩展名:

extension Data {

    var hexString: String {
        return map { String(format: "%02hhx", $0) }.joined()
    }

    var decimalString: String {
        return map { String(format: "%d", $0) }.joined()
    }

}

Your test string "UK" 您的测试字符串“ UK”

let string = "UK"

Evaluates with

let hexString = string.data(using: .ascii)!.hexString

To

554b

And with

let decimalString = string.data(using: .ascii)!.decimalString

To

8575

Both results are correct, you can look them up in any ASCII table. 两种结果都是正确的,您可以在任何ASCII表中查找它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM