You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字节数据转换为十六进制字符串再转成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 HexEncodingOptions struct gives you control over whether the output uses uppercase or lowercase hex characters.
  • For each byte in the Data object, 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 reserveCapacity upfront optimizes performance by preallocating exactly the space needed for the output string (2 characters per byte).

内容的提问来源于stack exchange,提问作者tp2376

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:36:26