本文介绍了如何快速将Int16转换为两个UInt8字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些二进制数据,该数据将两个字节的值编码为有符号整数.
I have some binary data that encodes a two byte value as a signed integer.
bytes[1] = 255 // 0xFF
bytes[2] = 251 // 0xF1
解码
这很容易-我可以使用以下命令从这些字节中提取Int16
值:
Int16(bytes[1]) << 8 | Int16(bytes[2])
编码
这是我遇到问题的地方.我的大多数数据规范都要求UInt
,这很容易,但是我在提取组成Int16
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
let nv : Int16 = -15
UInt8(nv >> 8) // fail
UInt8(nv) // fail
问题
如何提取构成Int16
值的两个字节
推荐答案
您应使用无符号整数:
let bytes: [UInt8] = [255, 251]
let uInt16Value = UInt16(bytes[0]) << 8 | UInt16(bytes[1])
let uInt8Value0 = uInt16Value >> 8
let uInt8Value1 = UInt8(uInt16Value & 0x00ff)
如果要将UInt16转换为等效的Int16,则可以使用特定的初始值设定项来实现:
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)
反之亦然:
let uInt16Value: UInt16 = 65000
let int16Value = Int16(bitPattern: uInt16Value)
在您的情况下:
let nv: Int16 = -15
let uNv = UInt16(bitPattern: nv)
UInt8(uNv >> 8)
UInt8(uNv & 0x00ff)
这篇关于如何快速将Int16转换为两个UInt8字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!