GP32 What do these colons mean ?


ConsoleTom

Member
Joined
Dec 4, 2003
Messages
106
Age
47
Location
Germany
Website
Visit site
Hi !

I have a structure and i don't understand what the numbers after the colons
mean (UBYTE Pause:1). Could anyone tell me please ?

typedef unsigned char UBYTE;

typedef struct
{
union
{
struct
{
UBYTE Pause:1;
UBYTE Cart0IO:1;
UBYTE Cart1IO:1;
UBYTE spare:5;
}Bits;
UBYTE Byte;
};
}TSWITCHES;

Greetings
Tobias
 
C and C++ are full of these hidden syntaxes that nobody understands, like presetting values in class constructors.

From the looks of it, this union contains two interfaces to a byte of data. Byte returns the full byte. Pause, cart, spare etc. return single bits of the byte. Since there are 8 bits in a byte, 1+1+1+5 = 8.

Still guessing: the union means that the byte and the struct of four variables point to the same location in memory. I assume that accessing 'Pause' will return a byte with value 0 or 1 depending on the value of the bit in memory.

To illustrate further because I suck at explaining: assume that we do this:

struct TSWITCHES foo;

Then:

foo.Byte = 54; // 00110110 in binary

foo.Bits.Pause == 0
foo.Bits.Cart0IO == 0
foo.Bits.Cart1IO == 1
foo.Bits.spare == 22 // 10110 in binary, the last 5 bits

Someone tell me if I am wrong...
 
foo.Byte = 54; // 00110110 in binary

foo.Pause == 0
foo.Cart0IO == 0
foo.Cart1IO == 1
foo.spare == 22 // 10110 in binary, the last 5 bits
shouldn't that be

foo.Bits.Pause == 0
foo.Bits.Cart0IO == 0
foo.Bits.Cart1IO == 1
foo.Bits.spare == 22

?

not sure though, i rarely use unions, and i never use bitfields.
 
Last edited by a moderator:
Be careful!

Bit fields are notoriously non-portable. A compiler may allocate the bits from the low end or the high end, so relying on the byte value is only safe if you are sure how your compiler works and you will only ever be using that compiler.

For example, if the compiler was allocating bits from the low end, then after doing
Code:
foo.Bits.Pause == 0 // bit 0
foo.Bits.Cart0IO == 0 // bit 1
foo.Bits.Cart1IO == 1 // bit 2
foo.Bits.spare == 22 // bits 7:3
the value of foo.Byte would be 0xB4 or 180.
 
Back
Top