Convert bytes/UInt8 array to Int in Swift

前端 未结 7 574
野性不改
野性不改 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:12

    In Swift 3 it is now a bit more wordy:

    let array : [UInt8] = [0, 0, 0, 0x0E]
    let bigEndianValue = array.withUnsafeBufferPointer {
             ($0.baseAddress!.withMemoryRebound(to: UInt32.self, capacity: 1) { $0 })
    }.pointee
    let value = UInt32(bigEndian: bigEndianValue)
    

提交回复
热议问题