# ASCII binary conversion

Discussion in 'Assembly Language Programming (ALP) Forum' started by laguna92651, Oct 22, 2009.

1. ### laguna92651New Member

Joined:
Oct 22, 2009
Messages:
4
0
Trophy Points:
0
I need to write an assembly language program for the MC68HC12 processor to convert an ASCII string into the appropriate 8 bit signed number that represents the ASCII string. Can someone give me some direction on this?

2. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,012
203
Trophy Points:
0
Occupation:
Senior Support Engineer
Location:
England
If you scan the string left to right then the algorithm is fairly simple: sum=10*sum+(digit-'0'), so multiply what you've got by 10, then add the numeric value of the digit, which can be obtained by subtracting the ASCII code of '0' from the ASCII code of the digit in question, because in ASCII the digits are helpfully arranged so that '1'='0'+1, '2'='0'+2 and so on. And of course '0'-'0'=0. sum starts out as zero, of course.

So let's take the string '123'. sum=0, and the first character is '1'. '1'-'0'=1, so sum*10+1=1.
Second character is '2', so sum=1*10+2=12.
And so on to '3' where sum=12*10+3=123.

If you haven't got a multiply instruction then you can do shifts and adds to get the desired result. x*10=x*8+x*2, so you can shift x left 1, copy that to the result, then shift it left twice more and add that to the result, i.e.
sum=0
shift left x 1 (x now contains 2* the original x)
add x to sum (sum now contains x*2)
shift left x 1
shift left x 1 (x now contains 8* the original x)
add x to sum (sum now contains x*2+x*8, or x*(2+8), or 10x).

If you want to be able to handle negative numbers as well then simply note somewhere if the first character is a minus, then at the end of the conversion just 2's complement the result (or flip all the bits and add 1, which is the same thing). So 123 is 7b in hex and 0111 1011 in binary, and -123 is 1000 0101.

3. ### laguna92651New Member

Joined:
Oct 22, 2009
Messages:
4
0
Trophy Points:
0
Thanks for your help, got it coded and working great, even took care of a negative number. Can you explain what the computation is doing to make the conversion or point me to an article. I tried googling it and couldn't find anything that was clear.

4. ### xpi0t0sMentor

Joined:
Aug 6, 2004
Messages:
3,012
203
Trophy Points:
0
Occupation:
Senior Support Engineer
Location:
England
digit contains the ASCII value of the digit. So if digit=='1' then the value of digit is 49 (you can find these numbers at various places, e.g. http://en.wikipedia.org/wiki/ASCII ). '0' is 48, so digit-'0' is 1, so we have converted '1' to 1.

sum=sum*10+digit, that just builds the number up as we encounter more digits.
So at '1', sum=0*10+1=1. At '2', sum=1*10+2=12. At '3', sum=12*10+3=123.
So for each digit we encounter we multiply sum by 10 and add the new digit.