如何在Swift3中将ASCII转换为十六进制?
问题描述:
我已经使用下面的代码将字符串“UK”转换为十六进制。我如何将它转换为十六进制?如何在Swift3中将ASCII转换为十六进制?
let str = auxText
let bytes = str.utf8
var buffer = [UInt8](bytes)
buffer[0] = buffer[0] + UInt8(1)
print("ascii value is",buffer)
答
在斯威夫特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表。
可能重复https://stackoverflow.com/questions/24229505/how-to-convert-an-int-to-hex-string-in-swift – Bilal
类似的问题可以在[Swift2](https:/ /stackoverflow.com/questions/32884783/swift-2-how-to-encode-from-ascii-to-hexadecimal)和[Linux](https://stackoverflow.com/questions/36441684/convert-ascii-to-十六进制和后退快速进行linux)研究,请看看并尝试。那么你可以避免被标记为重复。 –
not working.My ascii值是[85,75],我没有得到期望值 – shivadeep