[英]Swift Convert Hex String or Character to Integer
I have a data source that is passing me a hex string (such as 11C01) that I need to convert each character in it into an integer or byte value so that I can use it as a bit field (ie doing things like value | 0x01 == 0 like you would in old C-style bit fields).我有一个数据源,它传递给我一个十六进制字符串(例如 11C01),我需要将其中的每个字符转换为整数或字节值,以便我可以将其用作位字段(即执行诸如 value | 0x01 之类的操作) == 0 就像在旧的 C 风格位域中一样)。 The language for this will be Swift.
用于此的语言将是 Swift。
For the life of me I cannot find a way to convert a character containing a hex value into an integer without doing some weird round-about putting into NSData then converting it from there or doing it using C in an Objective-C class.在我的一生中,我找不到一种方法来将包含十六进制值的字符转换为整数,而不需要做一些奇怪的轮回放入 NSData 然后从那里转换它或在 Objective-C 类中使用 C 来做。 Just looking for something in Swift to do this instead of resorting to that.
只是在 Swift 中寻找一些东西来做到这一点,而不是诉诸于那个。
A sample string would be this: 11C01 I need it to create an array of bytes or integers like this: 0x1, 0x1, 0xC, 0x0, 0x1.一个示例字符串是这样的: 11C01 我需要它来创建一个字节或整数数组,如下所示:0x1, 0x1, 0xC, 0x0, 0x1。
The output should be an int or byte that I can do the bitwise operation on.输出应该是一个整数或字节,我可以对它进行按位运算。
How would I go about doing this?我该怎么做呢?
Thanks in advance!提前致谢!
edit/update:编辑/更新:
Swift 5 or later you can use Character property hexDigitValue: Swift 5 或更高版本,您可以使用 Character 属性 hexDigitValue:
let hexaString = "11C01"
let integers = hexaString.compactMap(\.hexDigitValue)
let bytes = integers.map(UInt8.init)
let hexaArray = hexaString.map { "0x" + String($0) }
print(integers) // "[1, 1, 12, 0, 1]"
print(bytes) // "[1, 1, 12, 0, 1]"
print(hexaArray) // "["0x1", "0x1", "0xC", "0x0", "0x1"]\n"
To convert every 2 characters into a byte (hexa to byte):要将每 2 个字符转换为一个字节(六到字节):
extension Collection {
func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
sequence(state: startIndex) { start in
guard start < self.endIndex else { return nil }
let end = self.index(start, offsetBy: maxLength, limitedBy: self.endIndex) ?? self.endIndex
defer { start = end }
return self[start..<end]
}
}
}
extension StringProtocol {
var byte: UInt8? { UInt8(self, radix: 16) }
var hexaToBytes: [UInt8] { unfoldSubSequences(limitedTo: 2).compactMap(\.byte) }
var hexaToData: Data { .init(hexaToBytes) }
}
"11C011".hexaToBytes // [17, 192, 17]
"11C011".hexaToData // 3 bytes
[0x11, 0xC0, 0x11] // [17, 192, 17]
let int_value = UInt64("11c01", radix: 16)
Then can shift the bits out然后可以将位移出
NOTE: Make sure data type can hold value注意:确保数据类型可以保存值
For the purposes of fun rather than clarity:为了好玩而不是为了清晰:
let hex_string = "11C01"
let result = map(hex_string.utf8) {
$0 & 0xf + $0 >> 6 | ($0 & 0x40) >> 3
}
// result: UInt8 array: [1, 1, 12, 0, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.