如何将UInt16转换为整数

时间:2018-01-17 06:47:22

标签: bit-manipulation swift4

我面临转换问题,我有2个UInt8字节,并使用

转换为UInt16
 let testLiveSpeed : UInt16
 let bytes: [UInt8] = [data[3], data[4]] //where data has contain array of `UInt8`, 
 self.testLiveSpeed = UnsafePointer(bytes).withMemoryRebound(to: UInt16.self, capacity: 1) {
      $0.pointee
 }  

但是self.testLiveSpeed它给出了无符号整数值,但我想要签名的Int值。请帮忙

1 个答案:

答案 0 :(得分:0)

请使用以下代码:

let  testLiveSpeed : Int16
let data: [UInt8] = [1, 1, 1, 127, 255]
let bytes: [UInt8] = [data[3], data[4]] 
testLiveSpeed = UnsafePointer(bytes).withMemoryRebound(to: Int16.self, capacity: 1) {
            $0.pointee
        }
print(testLiveSpeed);