How in swift to convert Int16 to two UInt8 Bytes

前端 未结 4 1555
甜味超标
甜味超标 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:23

    extension Int16 {
        var twoBytes : [UInt8] {
            let unsignedSelf = UInt16(bitPattern: self)
            return [UInt8(truncatingIfNeeded: unsignedSelf >> 8),
                    UInt8(truncatingIfNeeded: unsignedSelf)]
        }
    }
    
    var test : Int16 = -15
    test.twoBytes // [255, 241]
    

提交回复
热议问题