Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Assembly Language Programming (ALP) Forum (http://www.go4expert.com/forums/assembly-language-programming-forum/)
-   -   ASCII binary conversion (http://www.go4expert.com/forums/ascii-binary-conversion-t19858/)

laguna92651 22Oct2009 23:19

ASCII binary conversion
 
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?

xpi0t0s 23Oct2009 04:09

Re: ASCII binary conversion
 
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.

laguna92651 24Oct2009 04:09

Re: ASCII binary conversion
 
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.

xpi0t0s 26Oct2009 02:02

Re: ASCII binary conversion
 
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.


All times are GMT +5.5. The time now is 07:30.