# Bit field layout

## Recommended Posts

Hello, Does anyone know if there are any C standards with regard to the layout of bits in a bit field (most-significant to least significant or vice versa?) I'm trying to define a bit field like this one, and I need to make sure that the five-bit field goes into the most-significant bits of the DWORD
struct Foo
{
unsigned field1 : 9 ;
unsigned field2 : 9 ;
unsigned field3 : 9 ;
unsigned field4 : 5 ;  // This must go into the MSB
}

The VCPP documentation claims that microsoft's compiler allocates bit fields the way I want, but this is marked 'microsoft specific' and I'd like to know if there is a defined standard.

##### Share on other sites
Allocation and alignment of bit fields are implementation-defined, and may even bridge allocation units on some machines. They might be assigned left-to-right or right-to-left; so in other words, no, you cannot ensure field4 ends up using the five most-signifigant bits across implementations.

##### Share on other sites
Even though you say C, you mention VCPP, so I assume you can you C++. Looks like you need to manage multiple fields that span 32 bits. Why don't you just create a class that has a data member of type uint32_t, and then make accessor functions to get/set the fields you need?

##### Share on other sites
Quote:
 Original post by scottdewaldEven though you say C, you mention VCPP, so I assume you can you C++. Looks like you need to manage multiple fields that span 32 bits. Why don't you just create a class that has a data member of type uint32_t, and then make accessor functions to get/set the fields you need?

Thats probably what I'll end up doing, I was just looking for a way to avoid coding the bit twiddling myself.

JB

##### Share on other sites
Why does field4 have to be in the MSB? (And why don't similar restrictions apply to the other fields?)

##### Share on other sites

I actually need all of those fields ordered from LSB to MSB. This struct actually represents a pixel in a D3D10 shared-exponent texture, and so I need it to match the D3D10 bit layout.

##### Share on other sites
Have you considered using a union?

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627651
• Total Posts
2978406

• 10
• 12
• 22
• 13
• 33