0

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]
1

1 Answer 1

5

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.