如何在swift中将Int16转换为两个UInt8字节

时间:2015-09-28 20:03:08

标签: swift bit-manipulation

我有一些二进制数据,它将两个字节的值编码为有符号整数。

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

解码

这很简单 - 我可以使用以下命令从这些字节中提取Int16

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

编码

这是我遇到问题的地方。我的大多数数据规范都要求UInt,这很简单,但我无法提取构成Int16的两个字节

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

问题

如何提取构成Int16值的两个字节

4 个答案:

答案 0 :(得分:16)

你应该使用无符号整数:

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,那么你可以使用特定的初始值设定器来实现:

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)

答案 1 :(得分:7)

您可以使用init(truncatingBitPattern: Int16)初始化程序:

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

答案 2 :(得分:2)

我会这样做:

let a = UInt8(nv >> 8 & 0x00ff)  // 255
let b = UInt8(nv & 0x00ff)       // 241

答案 3 :(得分:0)

class ExampleClass(object):
    def __init__(self, filename = 'defaultFilename'):
        self.file_name = filename

    @staticmethod
    def doSomethingWithFiles(file_2, file_1 = None):
         #if user didn't supply a file use the instance variable 
         if file_1 is None:
            # no idea how to handle the uninitialized class case to create
            # self.file_name. 
            file_1 = __class__.__init__().__dict__['file_name'] <--- this seems sketchy
         else:
            file_1 = file_1
         with open(file_1, 'r') as f1, open(file_2, 'w') as f2:
            .....you get the idea...

    def moreMethodsThatUseSelf(self):
        pass