1

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

2
  • 2
    Why do you transfer the values as a string? Send each value as 1 or 2 bytes (depending on the required precision). Commented Oct 25, 2016 at 22:35
  • 1
    Btw, is not a valid ASCII character. Commented Oct 26, 2016 at 8:34

1 Answer 1

1

(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.

Sign up to request clarification or add additional context in comments.

3 Comments

So was the downvote because my answer was wrong or because I answered the question as it was asked even while acknowledging there was a better approach to the OP's problem?
I'm really sorry, I'm not sure how the downvote was triggered and I assure you it was not intentional, hopefully I've corrected it. I'm not sure if it was me that triggered the downvote. I'm just tried your solution and have to thank you as it does answer my question.
Actually, I had assumed it was a passer-by. Looking at the vote history, it seems that's the case, given one down vote and one upvote, but thanks for voting to offset. :-) Give consideration to the comment to your question though, a single byte would scale to 4-5 volts very wrll while savint tons of data. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.