If you have ever programmed in Pascal or C, you may be familiar with the concept of a Union. A Union is similar in some ways to a User-Defined Type. Both have data fields that can be made up of any of PowerBASIC's data types, including records and other Unions, and except for the UNION keyword, they are defined the same way. The major difference between User-Defined Types and Unions, is that each field within a Union occupies the same memory location as all the others.
While the concept may appear abstract, Unions provide an avenue to freely convert data from one format to another, simply by writing the data into the Union as one data format, and reading the data back as another. Combining the versatility of a UDT with the flexibility of a Union can extend this functionality dramatically, such as splitting data into its component parts.
For example, the following definition would create a Union called WordFld and a WordFld variable called MyVar:
Lo AS BYTE
Hi AS BYTE
Whole AS WORD
Part AS HiLo
DIM MyVar AS WordFld
MyVar.Whole = &HBC1F 'assign a value to the entire word
a$ = HEX$(MyVar.Part.Hi) 'returns Hi byte of the word
b$ = HEX$(MyVar.Part.Lo) 'returns Lo byte of the word
When you access the field MyVar.Whole, you are reading the entire contents of the Union as a word. On the other hand, when you refer to MyVar.Part.Hi, you are referring to the high byte of MyVar.
User-Defined Types (UDTs)
Union Storage requirements and restrictions