How in swift to convert Int16 to two UInt8 Bytes

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

    You should work with unsigned integers:

    let bytes: [UInt8] = [255, 251]
    let uInt16Value = UInt16(bytes[0]) << 8 | UInt16(bytes[1])
    let uInt8Value0 = uInt16Value >> 8
    let uInt8Value1 = UInt8(uInt16Value & 0x00ff)
    

    If you want to convert UInt16 to bit equivalent Int16 then you can do it with specific initializer:

    let int16Value: Int16 = -15
    let uInt16Value = UInt16(bitPattern: int16Value)
    

    And vice versa:

    let uInt16Value: UInt16 = 65000
    let int16Value = Int16(bitPattern: uInt16Value)
    

    In your case:

    let nv: Int16 = -15
    let uNv = UInt16(bitPattern: nv)
    
    UInt8(uNv >> 8)
    UInt8(uNv & 0x00ff)
    

提交回复
热议问题