Reputation: 3352
I have an array UInt8, I want to convert a hex number to decimal 2's complement:
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
According to this site https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=0xC8
0xc8: Decimal number = 200
Decimal from signed 2's complement = -56
In my code when I print it:
[36, 23, 101, 0, 0, 0, 0, 200, 0, 200, 0, 32, 3, 7, 0, 3, 200]
But I do not want it to be 200 but -56
Here is the result I want:
[36, 23, 101, 0, 0, 0, 0, 200, 0, 200, 0, 32, 3, 7, 0, 3, -56]
How to do this?
Upvotes: 2
Views: 844
Reputation: 3817
Your array is currently of type [UInt8]
- it can't hold a value of -56
.
Try this instead:
var command = [Int8]()
command.append(Int8(bitPattern: 0x24))
...
command.append(Int8(bitPattern: 0xc8))
Or transform what you already have:
let signedCommand = command.map { Int8(bitPattern: $0) }
Upvotes: 3