User Tools

Site Tools


simulating_20a_20union

Simulating a union

by Richard Russell, March 2007

BBC BASIC doesn't have unions, but it is possible to simulate them using structures. The trick is to create two (or more) structures, which should be the same size, then manipulate the internal pointers such that both structures refer to the same data.

Here is a simple example of creating a union between a 32-bit integer value and four individual 8-bit values:

        DIM s1{v%}
        DIM s2{b0&,b1&,b2&,b3&}
        !(^s2{}+4) = s1{}
 
        s1.v% = &12345678
 
        PRINT ~s2.b0& s2.b1& s2.b2& s2.b3&

Here the structure s1{} contains the 32-bit integer value s1.v% and the structure s2{} contains the four 8-bit values s2.b0&, s2.b1&, s2.b2& and s2.b3&. The third line is a bit of 'magic' which sets s2{} to point to the same data as s1{}.

Hence you can write and read the data using either of the two formats. In the example above the data is written as a single 32-bit value and read as four 8-bit values.

If you prefer to hide the non-obvious 'magic' code away from public gaze, you can put it in a procedure (which could even be contained in a library) as follows:

        DIM s1{v%}
        DIM s2{b0&,b1&,b2&,b3&}
        PROCunion(s1{}, s2{})
 
        s1.v% = &12345678
 
        PRINT ~s2.b0& s2.b1& s2.b2& s2.b3&
        END
 
        DEF PROCunion(a{}, RETURN b{})
        !(^b{}+4) = a{}
        ENDPROC

Note that, unlike languages which have true unions, this technique will not save memory. The memory originally allocated to the structure s2{} is wasted, but that doesn't matter if it is a LOCAL structure since the memory will be released on exit from the procedure or function in which it was declared.

This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
simulating_20a_20union.txt · Last modified: 2018/04/17 18:48 by tbest3112