0

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.

Eric Aya
  • 68,765
  • 33
  • 165
  • 232
Evgeniy Kleban
  • 6,102
  • 12
  • 43
  • 89

3 Answers3

2

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.

JeremyP
  • 80,230
  • 15
  • 117
  • 158
  • You could use `insert(_ newElement: UInt8, at i: Int)` instead of `append` while adding elements, so that you don't have to reverse it – user1046037 Oct 20 '19 at 12:02
2

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
Martin R
  • 488,667
  • 78
  • 1,132
  • 1,248
  • i tried let rCode = 94887253 let arr = Array(String(rCode).utf8) print("arr? \(arr)") but ended up with - [57, 52, 56, 56, 55, 50, 53, 51] – Evgeniy Kleban Sep 13 '17 at 10:13
  • 2
    @EvgeniyKleban which is the same array. 57 in base 10 is `0x39` in hex. – JeremyP Sep 13 '17 at 10:16
  • @EvgeniyKleban That's why I added the print statement: to demonstrate that the result is what you are looking for. – Martin R Sep 13 '17 at 10:21
1

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.

Dávid Pásztor
  • 40,247
  • 8
  • 59
  • 80