Duncan Hill
Duncan Hill

Reputation: 547

Swift - String / Character to ASCII, Int value

I need to convert each character of a string into it's equivalent ASCII value / integer value. Each string contains six characters similar to the following:

var str = "20‰/<;"

Using the above string I'm expecting 50, 48, 137, 47, 60, 59, I'm able to extract each character but struggling to convert the character to it's integer ASCII value.

BACKGROUND : The string represents 6 voltage values from an Arduino, transferred from the Arduino to the iPhone using Bluetooth LE serial connection. Initially I was attempting to transfer a string similar to '5.0,4.8,13.7,4.7,6.0,5.9' but discovered that BLE has a 20 byte transfer limit. As a result I decided that if I multiply the voltage values by 10 and then convert them to a character on the Arduino would reduce the data transferred to just 6 bytes. My challenge is then converting the character back to the voltage float value.

If anyone has a better or alternative way of transferring the 6 voltage values from the Arduino to the iPhone I'd be interested. The voltage range will between 0 - 18 volts

Upvotes: 1

Views: 2948

Answers (1)

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

(Answering the question you asked but the comment is valid: A single byte can represent any range with a little math...)

From the docs:

for codeUnit in someString.utf8 {
    print("\(codeUnit) ", terminator: "")
}

Should print out a space-separated list of ASCII character numbers.

Because UTF8 represents ASCII characters, the UTF8 code unit of each character should give you what you need.

Upvotes: 1

Related Questions