# How to convert ASCII to binary to facilitate a UART to SPI bridge for an MSP430?

I am currently working on project where the commands for a PC to the MSP430 will be communicated via UART. These commands need to be converted to binary to be able to written to the SPI bus.

For example 'a' from PC is translated to 0x61 on the microcontroller. What is really needed is hex 'a' Thus
ASCII 'a' from PC = 0x61 => need to translate hex 0x0A

Question : What is the most simplest way to convert ASCII to binary? I am using "C".

• ASCII codes are just numbers. If you're defining the protocol for the SPI connection, couldn't you simply have your bridge echo the data from the USART to the SPI port? – Niall C. Aug 7 '15 at 0:49
• I seriously don't get your question. ASCII characters are just 1 byte -- you can simply put this byte on the TX buffer/line. What's the problem? Or are there details you didn't provide? – thejohnny Aug 7 '15 at 0:51
• So you want to convert a character representing a hexadecimal digit '0', '1' ... 'a' ... 'f' into the value of that digit (0x00, 0x01 ... 0x0A ... 0x0F)? – Niall C. Aug 7 '15 at 0:57
• Not clear what the question is but guessing its something like a protocol where binary data is transmitted as ascii hex? e.g. the byte with value 255 is transmitted as ascii "FF" so (decimal) 46, 46 travels on the wire? More details required. – Simon Jenkins Aug 7 '15 at 1:09
• Let's don't forget a truly simple way: table lookup. May be overkill, but I haven't seen the input/output mapping clearly defined for all cases. – Throwback1986 Aug 7 '15 at 2:47

The input from the PC is a character, i.e. an ASCII-value. To understand how this is saved, have a look at the ASCII-table. The numbers '0' to '9' are represented by the ASCII-codes 0x30 to 0x39. The capital letters 'A' to 'Z' are represented by 0x41 to 0x5A, and the small letters 'a' to 'z' by 0x61 to 0x7A.

You could of course use a function like sscanf, as suggested by @JohnO'M. Such functions (printf, scanf, ...) have many features but thus require a lot of power and memory[Citation needed], which we often don't want to spend on a microcontroller. A simple alternative would be to distinguish the 3 possible cases (0-9 or A-F or a-f) and subtract the correct number from the ASCII code to get to the result:

if( (s >= 0x30) && (s <= 0x39)) {        // 0-9
x = s - 0x30;
}
else {
if( (s >= 0x41) && (s <= 0x46)) {    // A-F
x = s - 0x37;
}
else {
if( (s >= 0x61) && (s <= 0x66)) { // a-f
x = s - 0x57;
}
else {                            // wrong input
x = 0xFF;
}
}
}