【问题标题】:How to convert ASCII to hex in Swift3?如何在 Swift3 中将 ASCII 转换为十六进制?
【发布时间】:2017-11-18 21:17:40
【问题描述】:

我已使用以下代码将字符串“UK”转换为十六进制。如何将其转换为十六进制?

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

【问题讨论】:

  • 类似问题可以在Swift2Linux研究中找到,看看试试。这样就可以避免被标记为重复。
  • 不工作。我的 ascii 值为 [85,75],我没有得到想要的值
  • 你期望什么hex形式?

标签: ios swift


【解决方案1】:

在 Swift 4 中,您可以将 ascii 编码的 string 转换为数据

string.data(using: .ascii)

要将数据转换为十六进制或十进制,您可以使用以下扩展名:

extension Data {

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

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

}

您的测试字符串“UK”

let string = "UK"

评估

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

554b

还有

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

8575

两个结果都是正确的,你可以在任何 ASCII 表中查找它们。

【讨论】:

    猜你喜欢
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2016-06-27
    相关资源
    最近更新 更多