Swift:从有符号2的补码Uint8到十六进制的十六进制数字

时间:2019-02-04 13:05:17

标签: swift bluetooth-lowenergy

我有一个数组UInt8,我想将一个十六进制数字转换为十进制2的补码:

var command = [UInt8]()
        command.append(0x24)
        command.append(0x17)
        command.append(UInt8(101))
        command.appendWithUint32Lsb(0)
        command.append(200)
        command.append(0)
        command.append(0xC8)
        command.append(0)
        command.append(0x20)
        command.append(3)
        command.append(7)
        command.append(0x00)
        command.append(UInt8(colors.count / 3))
        command.append(0xC8) <---- IR

根据该网站https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=0xC8

0xc8: 小数= 200

带符号2的补码中的小数= -56

在我打印代码时:

[36, 23, 101, 0, 0, 0, 0, 200, 0, 200, 0, 32, 3, 7, 0, 3, 200]

但是我不希望它是200,而是-56

这是我想要的结果:

[36, 23, 101, 0, 0, 0, 0, 200, 0, 200, 0, 32, 3, 7, 0, 3, -56]

该怎么做?

1 个答案:

答案 0 :(得分:2)

您的数组当前为[UInt8]类型-它的值不能为-56

尝试以下方法:

var command = [Int8]()
command.append(Int8(bitPattern: 0x24))
...
command.append(Int8(bitPattern: 0xc8))

或转换您已有的内容:

let signedCommand = command.map { Int8(bitPattern: $0) }
相关问题