Unit 12.4 -- Converting Character Strings to Binary
If we have a five-byte character string that presumably
represents a number, we can convert it to binary as follows:
for each character
convert it from EBCDIC to a binary integer, a number 0 through 9
multiply that binary integer by the appropriate power of ten.
add it to a running sum
The program below illustrates the operation in PASCAL.
We use register eight as a register-trick field. Note that we
start at the right hand side and go to the left, corresponding to
the fact that i is a "downto" loop.
Then the digit is extracted in line 17. with an IC instruction.
Lines 18 to 20 subtract the character zero from the position.
This will give us the binary form of the digit.
LIne 22 to 30 multiply the binary digit by the power of ten.
(The subroutine call a multiply routine. I used the STM and LM
as the multiply subroutine craps all over the registers and I
wanted to protect registers 0 to 5 from this so I could continue
using their values in the main program. If the subroutine
doesn't save the registers, e.g., by usingthe IBM convention,
then the main program had better obey CAVEAT CALLER.)
At line 31, register 11 will contain the product of the binary
form of the integer.
Line 33 adds this to the running sum.
Lines 36 to 45 multiply the current power of ten by ten. Thus
register 2 will have the values (1,10,100,1000,10000) as we
proceed through the loop.
program convertchartobinary(input,output);
var field:array[1..5] of char;
thebin,power10,i:integer;
begin
for i:=1 to 5 do begin
read(field[i]);
end;
{translation starts here}
i:=5;
power10:=1; {R2}
thebin:=0; {R4}
for i:=5 downto 1 do begin;
thebin:=thebin+power10*(ord(field[i])-ord('0'));
power10:=power10*10;
end;
{translation ends here}
write(thebin);
end.