How in swift to convert Int16 to two UInt8 Bytes

前端 未结 4 1559
甜味超标
甜味超标 2021-02-04 07:42

I have some binary data that encodes a two byte value as a signed integer.

bytes[1] = 255  // 0xFF
bytes[2] = 251  // 0xF1

Decoding

4条回答
  •  情深已故
    2021-02-04 08:25

    You could use init(truncatingBitPattern: Int16) initializer:

    let nv: Int16 = -15
    UInt8(truncatingBitPattern: nv >> 8) // -> 255
    UInt8(truncatingBitPattern: nv) // -> 241
    

提交回复
热议问题