Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


Bit fields

This topic is 5854 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi Guys Just been learning about bit fields in structures. One thing that has confused me a little bit. I have declared this structure:- struct { unsigned one: 1; unsigned two: 1; unsigned three: 1; unsigned four: 1; unsigned five: 1; unsigned six: 1; unsigned seven: 1; unsigned eight: 1; }var1; Now, for some reason I was under the impression that when I find the size of var1 using "sizeof" I thought the size would be 1 byte. But its 4. Why is this. Is there a way that I can make it smaller? I did try using char instead of unsigned but then if I want to hold the value "1" in a bit field it produces -1 on screen when I print the value. Is this because this single bit is treated as the high order bit which is normally reserved for the +/- sign? Someone please enlighten me.

Share this post

Link to post
Share on other sites
Also, MSVC aligns all structs to 4bytes.

//Only pack 1 byte!
#pragma pack(1)

struct {
unsigned char one: 1;
unsigned char two: 1;
unsigned char three: 1;
unsigned char four: 1;
unsigned char five: 1;
unsigned char six: 1;
unsigned char seven: 1;
unsigned char eight: 1;

Share this post

Link to post
Share on other sites
i tried this under MsVS.NET without #pragma pack(1)

struct dummy
unsigned char b0:1;
unsigned char b1:1;
unsigned char b2:1;
unsigned char b3:1;
unsigned char b4:1;
unsigned char b5:1;
unsigned char b6:1;
unsigned char b7:1;

printf( "sizeof( dummy ) = %d\n", sizeof( dummy ) );

and it gave me 1

Share this post

Link to post
Share on other sites
Unfortunately I'm not yet aware of the #pragma preprocessor directive.

Anyone care to explain it to me?

P.S. When I altered all the fields to unsigned char it did reduce the size to 1 byte but I still want to know what #pragma does.

[edited by - SteveBe on September 10, 2002 12:03:17 PM]

Share this post

Link to post
Share on other sites
#pragma is an instruction to the compiler... and totally compiler specific.

If you are using VC++ or VC.NET, check the MSDN for details. Otherwise check your compilers docs.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!