1

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

let u8: [UInt8] = [0x02, 0x02, 0x02]
Hamish
  • 78,605
  • 19
  • 187
  • 280
Gobi M
  • 3,243
  • 5
  • 32
  • 47
  • 1
    What have you tried? `UInt32` is initializable with `UInt8`. Are you looking for something more sophisticated than mapping this array onto the resulting one? – Losiowaty Apr 19 '17 at 13:56
  • See https://stackoverflow.com/questions/25267089/convert-a-two-byte-uint8-array-to-a-uint16-in-swift – Ortomala Lokni Apr 19 '17 at 13:59
  • 5
    `let u32 = u8.map{ UInt32($0) }` or do you want `[UInt8]` to `UInt32` (no array)? – vadian Apr 19 '17 at 14:01

2 Answers2

5

Try this

let u8: [UInt8] = [0x02, 0x02, 0x02]
let u32: [UInt32] = u8.map { UInt32($0)  }
print("u32: \(u32)")
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
0

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]
Okan TEL
  • 26
  • 3