'Convert [UInt8] to [UInt32] in Swift 3

How to Convert [UInt8] to [UInt32] in Swift 3?

let u8: [UInt8] = [0x02, 0x02, 0x02]


Solution 1:[1]

Try this

let u8: [UInt8] = [0x02, 0x02, 0x02]
let u32: [UInt32] = u8.map { UInt32($0)  }
print("u32: \(u32)")

Solution 2:[2]

I used bit shifting.You can try below code lines.

let bytes: [UInt8] = [41, 22, 91, 13, 85, 71, 12, 34]
func getU32Array(byteArr: [UInt8]) -> [UInt32]? {

let numBytes = byteArr.count
var byteArrSlice = byteArr[0..<numBytes]

guard numBytes % 4 == 0 else { print ("There is not a multiple of 4") ;return nil }

var arr =  [UInt32](repeating: 0, count: numBytes/4)
for i in (0..<numBytes/4).reversed() {
    arr[i] = UInt32(byteArrSlice.removeLast())  + UInt32(byteArrSlice.removeLast()) << 8 + UInt32(byteArrSlice.removeLast()) << 16 + UInt32(byteArrSlice.removeLast()) << 24
}
return arr
} 
print(getU32Array(byteArr: bytes)!)

//output: [689330957, 1430719522]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paulo Mattos
Solution 2