Bit field layout

Started by
5 comments, last by Dragon88 17 years, 4 months ago
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.
Joshua Barczak3D Application Research GroupAMD
Advertisement
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.
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?
<a href="http://www.slimcalcs.com>www.slimcalcs.com
Quote:Original post by scottdewald
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?


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

JB
Joshua Barczak3D Application Research GroupAMD
Why does field4 have to be in the MSB? (And why don't similar restrictions apply to the other fields?)

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.
Joshua Barczak3D Application Research GroupAMD
Have you considered using a union?

This topic is closed to new replies.

Advertisement