How to convert a 4-bytes array into the corresponding Int?
let array: [UInt8] ==> let value : Int
Example:
The problem with the accepted answer comes when you don't know the size of your bytes array (or your Data
size)
It works well with let array : [UInt8] = [0, 0, 0x23, 0xFF]
But it won't work with let array : [UInt8] = [0x23, 0xFF]
(because it will be considered as [0x23, 0xFF, 0, 0]
)
That's why I like the @Jerry's one, with bitwise operation.
I've made a functional version of his code snippet.
let data = Data(bytes: [0x23, 0xFF])
let decimalValue = data.reduce(0) { v, byte in
return v << 8 | Int(byte)
}