gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:07:33 28 4
gpt4 key购买 nike

我有一个 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]

如何做到这一点?

最佳答案

您的数组当前是 [UInt8] 类型 - 它不能包含 -56 的值。

试试这个:

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

或者改造你已有的:

let signedCommand = command.map { Int8(bitPattern: $0) }

关于Swift:从有符号 2 的补码 Uint8 到十进制的十六进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54516773/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com