How in swift to convert Int16 to two UInt8 Bytes

十年热恋 提交于 2019-12-02 23:20:32

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)

You could use init(truncatingBitPattern: Int16) initializer:

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

I would just do this:

let a = UInt8(nv >> 8 & 0x00ff)  // 255
let b = UInt8(nv & 0x00ff)       // 241
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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!