views:

523

answers:

4

If I have a C++ struct, defining a 64bit data word such as..

struct SMyDataWord
{
    int Name : 40;
    int Colour : 24;
};

What does the : 40 syntax mean... does it mean that the first 40 bits are reserved for the Name and the remaining 24 bits for the Colour?

This is how it appears to be being used, but I've not come across it before.

+5  A: 

Bitfields, carried over from C. Name is 40 bits wide, Colour is 24 bits wide. Your struct therefore has at least 64 bits. On my system 64 bits would be 8 bytes.

dirkgently
On what system would 64bits not be 8 bytes?
Dave Van den Eynde
To be pedantic, the number of bits in a byte is implementation dependent (see either of the C, C++ standard). This is given by the CHAR_BIT macro in the 'limits' header.
dirkgently
Some IBM mainframes have had 9bit bytes, IIRC.
Steve Jessop
... and on such systems (where a byte is a multiple of 3) do octals wield their superiority when doing bit fiddling (yes, I know, I digress).
dirkgently
+4  A: 

Yes, that is the syntax for bitfields. They are commonly used to define structs that map onto hardware registers. There are some things to keep in mind if you decide to use them, one is that you can't know how the compiler does the layout, ordering and padding in the actual bytes making up the fields can and will differ among compilers (and perhaps with the same compiler but with different optimization settings, too).

unwind
+3  A: 

That's a bitfield definition.

Name is an integer that's able to store exactly 40 bits of information. Colour can store 24 bits.

This is often done to save some space in often needed structures, or compress code down to a size that's easy to handle for the CPU (in your case 64 bits. Fit's exactly into a CPU register on a 64 bit machine).

The code that accesses the bitfields will execute a tad slower though.

Nils Pipenbrinck
+1  A: 

Use them judiciously:

Remember that almost everything about bit fields is implementation dependent. For example, whether bits are stored left-to-right or right-to-left depends on the actual hardware architecture. Furthermore, each compiler uses a different member alignment model, which is why the size of the optimized BillingRec is 12 bytes rather than 9. You cannot take a bit field's address nor can you create an arrays of bits. Finally, on most implementations the use of bit fields incurs speed overhead. Therefore, when you optimize your code, measure the effect of a certain optimization and its tradeoffs before you decide to use it.

Comptrol