Evgeniy Kleban
Evgeniy Kleban

Reputation: 6965

Convert integer to array of UInt8 units

I have number - 94887253 (in ASCII), it can be represented like: let data = [UInt8]([0x39, 0x34, 0x38, 0x38, 0x37, 0x32, 0x35, 0x33])

How to write a function that convert number to such array of UInt8 units? Thanks.

Upvotes: 0

Views: 2966

Answers (3)

David Pasztor
David Pasztor

Reputation: 54755

If you want to get an ASCII codes of the decimal String representation of a number, you can write your own function for it like this:

func getAsciiCodesOfDigits(_ n: Int)->[UInt8]{
    return String(n).unicodeScalars.map{UInt8($0.value)}
}

getAsciiCodesOfDigits(numberToConvert)

Above function works, since using an Int as an input ensures that each element of String(n).unicodeScalars will be an ASCII character and hence it can be represented as a UInt8 and for ASCII characters, UnicodeScalar.value returns the ASCII code in a decimal form.

Upvotes: 0

JeremyP
JeremyP

Reputation: 86671

I would use shifts.

var array: [UInt8] = []
var n = theInputNumber
while n > 0
{
    array.append(UInt8(n & 0xff))
    n >>= 8
}

This is type safe and endian independent (the array is little endian but is easy to reverse) but slower than using an unsafe pointer.

EDIT

Right, so the question wasn't clear. If you want the ASCII represenatation of the number, the easy way is to turn it into a string and take the UTF-8

Array("\(theInputNumber)".utf8)

Or if you need to roll your own, modify my first answer

var array: [UInt8] = []
var n = theInputNumber
while n != 0
{
    array.append(UInt8(n % 10) + 0x30)
    n /= 10
}

The array is in reverse order, but I'll let you figure out how to get it the right way around.

Also will need modification for negative numbers.

Upvotes: 2

Martin R
Martin R

Reputation: 539975

It seems that what you are looking for is an array with the ASCII codes of the (decimal) string representation of the number:

let x = 94887253
let a = Array(String(x).utf8)

print(a == [0x39, 0x34, 0x38, 0x38, 0x37, 0x32, 0x35, 0x33]) // true

Upvotes: 1

Related Questions