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&}
        PTR (s2{)) = PTR(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 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.

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: 2024/01/05 00:21 by 127.0.0.1