简体   繁体   English

如何快速将Int16转换为两个UInt8字节

[英]How in swift to convert Int16 to two UInt8 Bytes

I have some binary data that encodes a two byte value as a signed integer. 我有一些二进制数据,将两个字节的值编码为有符号整数。

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

Decoding 解码

This is fairly easy - I can extract an Int16 value from these bytes with: 这相当简单-我可以使用以下命令从这些字节中提取一个Int16值:

Int16(bytes[1]) << 8 | Int16(bytes[2])

Encoding 编码方式

This is where I'm running into issues. 这是我遇到问题的地方。 Most of my data spec called for UInt and that is easy but I'm having trouble extracting the two bytes that make up an Int16 我的大部分数据规范都要求使用UInt ,这很简单,但是我在提取构成Int16的两个字节时遇到了麻烦

let nv : Int16 = -15
UInt8(nv >> 8) // fail
UInt8(nv)      // fail

Question

How would I extract the two bytes that make up an Int16 value 我将如何提取构成Int16值的两个字节

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: 如果要将UInt16转换为等效的Int16,则可以使用特定的初始化程序进行:

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: 您可以使用init(truncatingBitPattern: Int16)初始化程序:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM