Convert bytes/UInt8 array to Int in Swift

前端 未结 7 550
野性不改
野性不改 2020-12-01 03:56

How to convert a 4-bytes array into the corresponding Int?

let array: [UInt8] ==> let value : Int

Example:

Input:

         


        
相关标签:
7条回答
  • 2020-12-01 04:28

    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)
    }
    
    0 讨论(0)
提交回复
热议问题