Convert bytes/UInt8 array to Int in Swift

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

    Updated for Swift 5, two things to pay attention:

    • As [UInt8] is stored in a contiguous region of memory, there's no need to convert it to Data, pointer can access all bytes directly.

    • Int's byte order is little endian currently on all Apple platform, but this is not garanteed on other platforms.

    say we want [0, 0, 0, 0x0e] to convert to 14. (big-endian byte order)

    let source: [UInt8] = [0, 0, 0, 0x0e]
    let bigEndianUInt32 = source.withUnsafeBytes { $0.load(as: UInt32.self) }
    let value = CFByteOrderGetCurrent() == CFByteOrder(CFByteOrderLittleEndian.rawValue)
        ? UInt32(bigEndian: bigEndianUInt32)
        : bigEndianUInt32
    print(value) // 14
    

提交回复
热议问题