Advertisement

Bit fields

Started by September 10, 2002 10:33 AM
4 comments, last by SteveBe 22 years, 3 months ago
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.
unsigned stands for unsigned int ...
... int are 4bytes long on 32bits platforms.

use unsigned char instead
Advertisement
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;
}var1;
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
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]
#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
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

This topic is closed to new replies.

Advertisement