Python struct.unpack ("i", bytearray(data)) 到 Swift 4

标签 python swift

Python:

data = [0,0,0,0]
data[3]= self.i2cbus.read_byte_data(self.i2cadd, add)
data[2]= self.i2cbus.read_byte_data(self.i2cadd, add+1)
data[1]= self.i2cbus.read_byte_data(self.i2cadd, add+2)
data[0]= self.i2cbus.read_byte_data(self.i2cadd, add+3)
value = struct.unpack("i", bytearray(data))
return value[0]

如何快速做到这一点?到目前为止我已经做到了。

var data: [UInt8] = [0,0,0,0]
data[3] = i2c.readByte(address, command: command) ?? 0
data[2] = i2c.readByte(address, command: command + 1) ?? 0
data[1] = i2c.readByte(address, command: command + 2) ?? 0
data[0] = i2c.readByte(address, command: command + 3) ?? 0

使用: https://github.com/uraimo/SwiftyGPIO

就是这个

    value = struct.unpack("i", bytearray(data))

我不知道该怎么办。

最佳答案

试试这个:

var value : UInt32 = 0
let nsdata = NSData(bytes: data, length: 4)
nsdata.getBytes(&value, length: 4)
value = UInt32(bigEndian: value)

关于Python struct.unpack ("i", bytearray(data)) 到 Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53890452/

相关文章:

swift - 如何将带参数的闭包传递给函数? ( swift )

ios - swift 1.2 : fatal error: unexpectedly found nil while unwrapping an Optional value

ios - 解析服务器云代码错误 141 无效函数

python - Pandas groupby 具有自定义函数以数组形式返回列值

Python 线程名称未显示在 ps 或 htop 上

python - 返回对应于行中最大值的列标题

python - Python中的默认参数是静态的吗?

python - 如何修复 "ValueError: Found input variables with inconsistent numbers of samples: [10000, 60000]"?

swift - 将 Swift 泛型类转换为具有类型别名的协议(protocol)

ios - 问题 找不到自动链接框架 'FirebaseMessaging'