如何将字节数据转换为十六进制字符串再转成32位有符号补码整数?
Convert Data to Hexadecimal String in Swift
Here's the complete implementation of the Data extension for converting to a hex string, including the truncated part from your snippet:
extension Data { struct HexEncodingOptions: OptionSet { let rawValue: Int static let upperCase = HexEncodingOptions(rawValue: 1 << 0) } func hexEncodedString(options: HexEncodingOptions = []) -> String { let hexDigits = Array((options.contains(.upperCase) ? "0123456789ABCDEF" : "0123456789abcdef").utf16) var chars: [unichar] = [] chars.reserveCapacity(2 * count) for byte in self { chars.append(hexDigits[Int(byte / 16)]) chars.append(hexDigits[Int(byte % 16)]) } return String(utf16CodeUnits: chars, count: chars.count) } }
Usage with Your Data
For your specific Data instance:
let data = Data(bytes: [206, 66, 49, 62]) // Lowercase hex string (default behavior) let lowercaseHex = data.hexEncodedString() print(lowercaseHex) // Output: "ce42313e" // Uppercase hex string let uppercaseHex = data.hexEncodedString(options: .upperCase) print(uppercaseHex) // Output: "CE42313E"
Quick Breakdown
- The
HexEncodingOptionsstruct gives you control over whether the output uses uppercase or lowercase hex characters. - For each byte in the
Dataobject, we split it into two 4-bit "nibbles", map each nibble to its corresponding hex digit, and build the final string from these characters. - Using
reserveCapacityupfront optimizes performance by preallocating exactly the space needed for the output string (2 characters per byte).
内容的提问来源于stack exchange,提问作者tp2376
相关产品推荐
相关产品推荐

