From Other Basics – VAL and LEN

Author(s): Richard Forsen
Publication: Syntax
Pub Details: Syntax/Syntax ZX80 v2 n9 (Volume 2, Issue 9)
Date: September 1981
Pages: 5

Microsoft BASIC is used by the Apple, TRS-80, and PET computers. Lots of software is available for these computers, so you can convert existing programs rather than write your own. This month we’ll look at 2 Microsoft BASIC keywords not offered in 4K ZX80 BASIC–LEN and VAL. When you find these commands in Microsoft programs, just substitute ZX80 BASIC commands.

LEN(N$) finds the number of characters in string N$. To simulate LEN in 4K BASIC, we use TL$, which strips a string of its first character. For example,

  20 INPUT S$
30 LET L=0
40 LET D$=S$
50 IF D$="" THEN GO TO 90
60 LET L=L+1
70 LET D$=TL$(D$)
80 GO TO 50
90 PRINT "THE STRING ";S$; HAS A LENGTH OF ";L;"."

Line 20 asks for the string and stores it as S$. The computer uses L to count characters; line 30 tells the ZX80 to start L out at 0. D$ is a working copy of S$, to be stripped by TL$. Each time the computer uses TL$, it checks to see if there’s anything left to the string, then adds 1 to L. This continues until D$ is empty. The above program in Microsoft BASIC looks like this (Don’t enter this in your 4K ZX80):

  20 INPUT S$
30 L=LEN(S$)
40 PRINT "THE STRING ";S$;" HAS A LENGTH OF ";L;"."
50 END

VAL(S$) changes string numerals to numbers. The ZX80 distinguishes NUMBERS, mathematical quantities, from NUMERALS, written representations of mathematical quantities. That is, “4” (Arabic) and “IV” (Roman) are both numerals meaning the square of 2 (a number). The computer stores numerals in quotation marks differently than it does numbers, so it can’t manipulate string numerals the same as it can numbers. Try the following VAL routine in 4K BASIC:

  10 INPUT S$
20 LET V=0
30 LET L=0
40 LET D$=S$
50 IF D$="" THEN GO TO 90
60 LET L=L+1
70 LET D$=TL$(D$)
80 GO TO 50
90 LET D$=S$
100 FOR I=1 TO L
110 LET V=V+(CODE(D$)-28)*10**(L-I)
120 IF I<L THEN LET D$=TL$(D$)
130 NEXT I
150 PRINT S$;" EQUALS ";V;"."

The first half of this routine is identical to our LEN program. Then, we use character codes to determine the number represented by each digit. Next we multiply it by a power of 10 determined by each digit’s position in the string.

The computer cannot, for instance, multiply a string by a number. VAL allows you to use numerals in strings, then convert them into numbers for the ZX80. The equivalent routine in Microsoft would be (again, your 4K machine won’t like this!):

  10 INPUT S$
20 LET V=VAL(S$)
40 PRINT S$;" EQUALS ";V;"."
50 END