User Tools

Site Tools


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&
        DEF PROCunion(a{}, RETURN b{})
        !(^b{}+4) = a{}

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. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
simulating_20a_20union.txt · Last modified: 2018/04/17 19:48 by tbest3112