简体   繁体   English

如何将包含各种类型int的数据转换成Swift Int

[英]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).我收到数据类型 object,其中包含 uint8_t、uint16_t、uint32_t(混合类型列表)的列表。 I need to convert this data into swift array of Int.我需要将此数据转换为 Int 的 swift 数组。 I cannot do the followings since data contains multiple types of int我无法执行以下操作,因为数据包含多种类型的 int

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

Data order数据顺序

  • data1: uint8_t数据 1:uint8_t
  • data2: uint32_t数据 2:uint32_t
  • data3: uint16_t数据 3:uint16_t

How can I convert this type of data into Swift array of Int如何将这种类型的数据转换为 Swift 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.由于Data是字节[UInt8] (大写 I)并且Data是可互换的。

For [uint16_t] and [uint32_t] use MartinR's Data extension对于[uint16_t][uint32_t]使用MartinR 的Data扩展

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]举个例子, uint16Bytes表示[UInt16]的数组,尽管类型是[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] . toArray返回[UInt16] You have to map the array to [Int]您必须将数组map设为[Int]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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