将 UInt16 拆分为 2 个 UInt8 字节并获取两者的六进制字符串。 Swift

Splitting a UInt16 to 2 UInt8 bytes and getting the hexa string of both. Swift

我需要将 16383 转换为 7F7F,但我只能将其转换为 3fff 或 77377。

我可以将 8192 转换为十六进制字符串 4000,两者本质上是一样的。

如果我使用 let firstHexa = String(format:"%02X", a) 第一个数字停在 3fff 十六进制,第二个数字停在 2000 十六进制。这是我的代码

public func intToHexString(_ int: Int16) -> String {
    var encodedHexa: String = ""
    if int >= -8192 && int <= 8191 {
        let int16 = int + 8192
        //convert to two unsigned Int8 bytes
        let a = UInt8(int16 >> 8 & 0x00ff)
        let b = UInt8(int16 & 0x00ff)
        //convert the 2 bytes to hexadecimals
        let first1Hexa = String(a, radix: 8 )
        let second2Hexa = String(b, radix: 8)
        let firstHexa = String(format:"%02X", a)
        let secondHexa = String(format:"%02X", b)

        //combine the 2 hexas into 1 string with 4 characters...adding 0 to the beggining if only 1 character.
        if firstHexa.count == 1 {
            let appendedFHexa = "0" + firstHexa
            encodedHexa = appendedFHexa + secondHexa
        } else if secondHexa.count == 1 {
            let appendedSHexa = "0" + secondHexa
            encodedHexa = firstHexa + appendedSHexa
        } else {
            encodedHexa = firstHexa + secondHexa
        }
    }
    return encodedHexa
}

请女士们先生们帮忙!谢谢

从您的测试用例来看,您的值似乎是每字节 7 位。

您希望 8192 转换为 4000。 您希望 16383 转换为 7F7F.

注意:

(0x7f << 7) + 0x7f == 16383

鉴于:

let a = UInt8((int16 >> 7) & 0x7f)
let b = UInt8(int16 & 0x7f)
let result = String(format: "%02X%02X", a , b)

这给出:

"4000" 对于 8128 "7F7F" 对于 16383


要反转该过程:

let str = "7F7F"
let value = Int(str, radix: 16)!
let result = ((value >> 8) & 0x7f) << 7 + (value & 0x7f)

print(result)  // 16383