by Richard Russell, March 2014
BBC BASIC for Windows provides two data types in which you can store a set of byte (8-bit, or character) values: one is the string (for example A$) and the other is the byte array (for example A&()). Both can contain arbitrary binary data (all possible 8-bit values are allowed) and both are limited in length only by the amount of available heap (this applies to BB4W version 6, in version 5 strings are limited to 65535 bytes).
The best choice of data type will often depend on the kind(s) of operation you intend to perform. For example if you want to search the data a string is likely to be the better choice, because you can use the INSTR function to do that. On the other hand if you want (for example) to add together all the data values an array is the better choice, because you can use the SUM function.
But what do you do if you want to perform, on the same data set, operations that are best suited to strings and operations that are best suited to arrays? There is a way, which is to create an array and a string which alias each other, that is each accesses the same data in memory! Here is how it can be done, assuming the data is initially stored in the 1-dimensional array byte&():
!^byte$ = ^byte&(0) !(^byte$+4) = DIM(byte&(),1) + 1
After execution of that code the string byte$ will alias the array byte&(). As shown the code is appropriate only for version 6 of BBC BASIC for Windows; for version 5 the maximum data size is 65535 bytes and the alias string must be created as follows:
!^byte$ = ^byte&(0) ?(^byte$+4) = DIM(byte&(),1) + 1 ?(^byte$+5) = (DIM(byte&(),1) + 1) >> 8
Note that array indexes are zero-based and string indexes are one-based so for example byte&(3) will have the same value as ASC(MID$(byte$,4)). If you find that confusing you can ignore the first element in the array and alias the string to the rest as follows (here for BB4W v6):
!^byte$ = ^byte&(0) + 1 !(^byte$+4) = DIM(byte&(),1)
Now the array and string indexes will align.
Do not attempt to change the length of the string; if you do that you will confuse BBC BASIC, and may well crash it. In particular do not empty the string (e.g. byte$ = ““); this means that you mustn't declare it as a LOCAL variable because BB4W will automatically empty it on exit from the function or procedure. However it should be safe to declare it as PRIVATE.
This is a powerful technique but it should be used with care.