1

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]

How to do it in swift? I havde done this so far.

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

Using: https://github.com/uraimo/SwiftyGPIO

It's the

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

I don't know how to do.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 2
    Possibly helpful: [round trip Swift number types to/from Data](https://stackoverflow.com/q/38023838/1187415). – Martin R Dec 21 '18 at 20:39

1 Answers1

0

Try this:

var value : UInt32 = 0
let nsdata = NSData(bytes: data, length: 4)
nsdata.getBytes(&value, length: 4)
value = UInt32(bigEndian: value)
KingHodor
  • 537
  • 4
  • 17
  • You should rather use an `UnsafeMutableRawPointer`. `NSData` is also outdated, and has been replaced by `Data`. The only reason I see people still using `NSData` for, is because of `getBytes`, but there's no need for it with pointers. – Andreas is moving to Codidact Dec 21 '18 at 23:18