简体   繁体   中英

How to convert data containing various types of int into Swift Int

I receive Data type object which inside is list of uint8_t, uint16_t, uint32_t(mix typed list). I need to convert this data into swift array of Int. I cannot do the followings since data contains multiple types of int

let list = [Uint8](data)
let list2 = [Int](data)

Data order

  • data1: uint8_t
  • data2: uint32_t
  • data3: uint16_t

How can I convert this type of data into Swift array of Int

You need to do type casting separately.

let list2 = [Int]()
for i in 0..<data.count {
    list2.append(Int(data[i]))
}

As Data are bytes [UInt8] (with capital I) and Data are interchangeable.

For [uint16_t] and [uint32_t] use MartinR's Data extension

extension Data {

    init<T>(fromArray values: [T]) {
        self = values.withUnsafeBytes { Data($0) }
    }

    func toArray<T>(type: T.Type) -> [T] where T: ExpressibleByIntegerLiteral {
        var array = Array<T>(repeating: 0, count: self.count/MemoryLayout<T>.stride)
        _ = array.withUnsafeMutableBytes { copyBytes(to: $0) }
        return array
    }
}

And an example, uint16Bytes represents an array of [UInt16] although the type is [UInt8]

let uint16Bytes : [UInt8] = [0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, 0x00]
let uint16Data = Data(uint16Bytes)

let array = uint16Data.toArray(type: UInt16.self).map(Int.init) // [1, 2, 3, 4]

toArray returns [UInt16] . You have to map the array to [Int]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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