QB64.com

QB64 is a modern extended BASIC programming language that retains QBasic/QuickBASIC 4.5 compatibility and compiles native binaries for Windows, Linux, and macOS.

The LEN function returns the number of bytes used by a variable value and the number of characters in a STRING.

Syntax

length% = LEN(literalTextOrVariable)

Example(s)

With a string variable the byte size is the same as the number of characters.


LastName$ = "Williams"
PRINT LEN(LastName$); "bytes" 


 8 bytes

Testing INPUT for numerical STRING entries from a user.


INPUT "number: ", num$

value$ = LTRIM$(STR$(VAL(num$)))
L = LEN(value$)

PRINT LEN(num$), L 

Note: &H, &O, D and E will also be accepted as numerical type data in a VAL conversion, but will add to the entry length.

With numerical value types you MUST use a variable to find the inherent byte length when using LEN.


DIM I AS INTEGER
PRINT "INTEGER ="; LEN(I); "bytes"
DIM L AS LONG
PRINT "LONG ="; LEN(L); "bytes"
DIM I64 AS _INTEGER64
PRINT "_INTEGER64 ="; LEN(I64); "bytes"
DIM S AS SINGLE
PRINT "SINGLE ="; LEN(S); "bytes"
DIM D AS DOUBLE
PRINT "DOUBLE ="; LEN(D); "bytes"
DIM F AS _FLOAT
PRINT "_FLOAT ="; LEN(F); "bytes" 


INTEGER = 2 bytes
LONG = 4 bytes
_INTEGER64 = 8 bytes
SINGLE = 4 bytes
DOUBLE = 8 bytes
_FLOAT = 32 bytes

Opening a RANDOM file using LEN to calculate and LEN = to designate the file record size.


TYPE variabletype
  x AS INTEGER'       '2 bytes
  y AS STRING * 10'  '10 bytes
  z AS LONG'          '4 bytes
END TYPE'            '16 bytes total
DIM record AS variabletype
DIM newrec AS variabletype

file$ = "testrand.inf" '<<<< filename may overwrite existing file
number% = 1 '<<<<<<<<<< record number to write cannot be zero
RecordLEN% = LEN(record)
PRINT RecordLEN%; "bytes"
record.x = 255
record.y = "Hello world!"
record.z = 65535
PRINT record.x, record.y, record.z

OPEN file$ FOR RANDOM AS #1 LEN = RecordLEN%
PUT #1, number% , record 'change record position number to add records
CLOSE #1

OPEN file$ FOR RANDOM AS #2 LEN = RecordLEN%
NumRecords% = LOF(2) \ RecordLEN%
PRINT NumRecords%; "records"

GET #2, NumRecords% , newrec 'GET last record available
CLOSE #2
PRINT newrec.x, newrec.y, newrec.z

END 


 16 bytes
 255        Hello worl       65535
 1 records
 255        Hello worl       65535

Explanation: The byte size of the record TYPE determines the LOF byte size of the file and can determine the number of records. To read the last record GET the number of records. To add a record, use the number of records + 1 to PUT new record data.

See Also