Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

size of custom structures using bitfield not as expected

Status
Not open for further replies.

Lucast85

Member level 3
Joined
Oct 19, 2009
Messages
62
Helped
4
Reputation
8
Reaction score
4
Trophy points
1,288
Location
Italy
Activity points
1,966
Hi all,
I'm doing some experiments to learn the bitfiled concept. I start with an example, but the size of the struct returned is not as much as i expected.
Code:
typedef struct{
		uint16_t	field1;
		uint8_t 	field2	:	7;
		uint8_t 	field3	:	1;
	}MyStruct_t;

	MyStruct_t	aStruct;

	printf("Size of aStruct= %d\n", sizeof(aStruct));
In fact, the program return that the size of such a structure is 4 bytes. I expect a size of 3 bytes because I used bitfield.
Maybe I'm missing something. What?
Thank you!
 

Presume you are running a processor requiring word allocation at even addresses. It will possibly fill up the structure to even byte size. The structure size actually matters when arranging it in larger structs or arrays. You can use "pack" pragma to allocate it differently, but possibly can't access the unt16 objects directly any more.
 
I'm running the program on an Intel i7 4700mq and MinGW-GCC v 4.8.1 toolchain under Eclipse IDE but I think I will use the defined struct also on Arduino Mega2560.
Are this sizes depending both by the architecture and by the compiler used?

Anyway, with a different example, the size appears to be correct:
Code:
	typedef struct{
		uint8_t		field1;
		uint8_t		field2;
		uint8_t 	field3	:	7;
		uint8_t 	field4	:	1;
	}MyStruct2_t;
	MyStruct2_t	aStruct2;
now the size is 3, as I actually expect.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top