Reputation: 3267
How to Convert [UInt8] to [UInt32] in Swift 3?
let u8: [UInt8] = [0x02, 0x02, 0x02]
Upvotes: 1
Views: 2417
Reputation: 78
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]
Upvotes: 1
Reputation: 15748
Try this
let u8: [UInt8] = [0x02, 0x02, 0x02]
let u32: [UInt32] = u8.map { UInt32($0) }
print("u32: \(u32)")
Upvotes: 5