Number Conversion in BASIC

From BeebWiki
Revision as of 19:12, 8 March 2015 by WikiSysop (talk | contribs) (1 revision)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

BASIC lets you display numbers in decimal or hexadecimal with the ~ prefix and converted to strings with STR$. These convert the number to a string consisting of the fewest characters needed.

When outputting fixed-width number strings, the following type of code is often seen:

 IF A<16 THEN PRINT "0";
 IF A<256 THEN PRINT "0";
 IF A<4096 THEN PRINT "0";
 PRINT ;~A

or even

 IF A<16 THEN PRINT "00";~A ELSE IF A<256 THEN PRINT "0";~A ELSE PRINT ~A

This is very inefficient and messy. The following functions allow conversion to fixed-width strings, and also to octal and binary, which are not supported by BASIC natively.

Hexadecimal Output

 REM Hexadecimal padded with zeros
 DEFFNh0(A%,N%)=RIGHT$("0000000"+STR$~A%,N%)
 :
 REM Hexadecimal padded with spaces
 DEFFNh(A%,N%)=RIGHT$("       "+STR$~A%,N%)

FNh0() converts the supplied number to a fixed width hexidecimal string padded with zeros, FNh() converts the supplied number to a fixed width hexidecimal string padded with spaces. For example, FNh0(10,6) returns 00000A.

Decimal Output

 REM Decimal padded with zeros
 DEFFNd0(A%,N%)=RIGHT$("00000000"+STR$A%,N%)
 :
 REM Decimal padded with spaces
 DEFFNd(A%,N%)=RIGHT$("         "+STR$A%,N%)

FNd0() converts the supplied number to a fixed width decimal string padded with zeros, FNd() converts the supplied number to a fixed width decimal string padded with spaces. For example, FNd0(10,6) returns 000010.

Octal Output

 REM Octal padded with zeros
 DEFFNo0(A%,N%):LOCAL A$,B%,L%:IFA%<0:B%=2:A%=A%AND&7FFFFFFF
 REPEATA$=STR$(A%AND7)+A$:A%=A%DIV8:L%=L%+3:UNTILL%>27:=RIGHT$(STR$(A%+B%)+A$,N%)
 :
 REM Octal padded with spaces
 DEFFNo(A%,N%):LOCAL A$:IFA%<0:=FNo0(A%,N%)
 REPEATA$=STR$(A%AND7)+A$:A%=A%DIV8:UNTILA%=0:=RIGHT$(STRING$(N%," ")+A$,N%)

FNo0() converts the supplied number to a fixed width octal string padded with zeros, FNo() converts the supplied number to a fixed width octal string padded with spaces. For example, FNo0(10,6) returns 000012.

Binary Output

 REM Binary padded with zeros
 DEFFNb0(A%,N%):LOCAL A$,B$,L%:IFA%<0:B$="1":A%=A% AND &7FFFFFFF ELSE B$="0"
 REPEAT A$=STR$(A%AND1)+A$:A%=A%DIV2:L%=L%+1:UNTILL%>30:=RIGHT$(B$+A$,N%)
 :
 REM Binary padded with spaces
 DEFFNb(A%,N%):LOCAL A$:IFA%<0:=FNb0(A%,N%)
 REPEAT A$=STR$(A% AND 1)+A$:A%=A%DIV2:UNTIL A%=0:=RIGHT$(STRING$(N%," ")+A$,N%)

FNb0() converts the supplied number to a fixed width binary string padded with zeros, FNb() converts the supplied number to a fixed width binary string padded with spaces. For example, FNb0(10,6) returns 001010.

See Also

BASIC Programming Library