简体   繁体   中英

Convert Int to Array of UInt8 in swift

I want to convert a standard integer in a list of UInt8 in swift.

var x:Int = 2019

2019 can be written (for example) in hexadecimal 7E3 so i want some kind of function that converts is to a list of UInt8s which looks like this.

var y:[Uint8] = [0x07, 0xE3]

I already found this: Convert integer to array of UInt8 units but he/she is convertign the ascii symbols of the number not the number itself. So his example 94887253 should give a list like [0x05, 0xA7, 0xDD, 0x55].

In the best case the function i'm looking for has some kind of usage so that i can also choose the minimum length of the resulting array so that for example

foo(42, length:2) -> [0x00, 0x2A]

or

foo(42, length:4) -> [0x00, 0x00, 0x00, 0x2A]

You could do it this way:

let x: Int = 2019
let length: Int = 2 * MemoryLayout<UInt8>.size  //You could specify the desired length

let a = withUnsafeBytes(of: x) { bytes in
    Array(bytes.prefix(length))
}

let result = Array(a.reversed()) //[7, 227]

Or more generally, we could use a modified version of this snippet :

func bytes<U: FixedWidthInteger,V: FixedWidthInteger>(
    of value    : U,
    to type     : V.Type,
    droppingZeros: Bool
    ) -> [V]{

    let sizeInput = MemoryLayout<U>.size
    let sizeOutput = MemoryLayout<V>.size

    precondition(sizeInput >= sizeOutput, "The input memory size should be greater than the output memory size")

    var value = value
    let a =  withUnsafePointer(to: &value, {
        $0.withMemoryRebound(
            to: V.self,
            capacity: sizeInput,
            {
                Array(UnsafeBufferPointer(start: $0, count: sizeInput/sizeOutput))
        })
    })

    let lastNonZeroIndex =
        (droppingZeros ? a.lastIndex { $0 != 0 } : a.indices.last) ?? a.startIndex

    return Array(a[...lastNonZeroIndex].reversed())
}

let x: Int = 2019
bytes(of: x, to: UInt8.self, droppingZeros: true)   // [7, 227]
bytes(of: x, to: UInt8.self, droppingZeros: false)  // [0, 0, 0, 0, 0, 0, 7, 227]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM