Click here to Skip to main content
15,896,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
struct pack
{
 unsigned int a:9;
} p;

And
struct pack
{
 unsigned int a;
} p;

Please explain the difference.
Thanks in advance.
Posted
Updated 30-Mar-11 8:35am
v3

In first sample a bit specifier is used.
Normally, if makes sense if you have a structure with more than one member with the bit specifier, such as ":9" in your sample.

It allows you to pack together some members which normally would use more bits then specified. The real reason for doing that is not saving of some memory. Rather, it is used to match exact binary layout of the structure required by some hardware, hardware API or binary compatibility with other 3rd-party code.

For detailed explanation, see: http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devwin32/bitfields_xml.html[^].

Pay special attention for Note on Compatibility — it is not a trivial issue.

—SA
 
Share this answer
 
v2
Comments
Monjurul Habib 30-Mar-11 15:03pm    
good call.5+
Sergey Alexandrovich Kryukov 30-Mar-11 15:15pm    
Thank you, Monjurul.
--SA
Espen Harlinn 30-Mar-11 15:05pm    
Good reply, my 5
Sergey Alexandrovich Kryukov 30-Mar-11 15:16pm    
Thank you, Espen.
--SA
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 30-Mar-11 14:31pm    
I provided more detailed answer before. Why would you add the Answer without adding any additional value?
--SA
twohowlingdogs 30-Mar-11 14:36pm    
I saw this question before you posted so I did not see your answer. All the information needed was in the link so I didn't think I needed to elaborate.
Sergey Alexandrovich Kryukov 30-Mar-11 15:24pm    
Understood, sure.
--SA
In the first example, you are explicitly saying how many bits of the integer should the value of "a" take up - bits 0 to 8 inclusive, for a total of 9.
In the second, you are saying that "a" occupies an entire unsigned int (usually 32 bits).

So if you had an instance of each strucure called "b" and you did this:
b.a = 0xffff;
printf("0x%x", (unsigned int) b);
Then the first way would print "0x1ff" and the second "0xffff";

You can use this to combine values into a single integer, or byte which can help with communications, either between processes or external hardware.
 
Share this answer
 
Comments
Monjurul Habib 30-Mar-11 15:02pm    
good call.5+
Sergey Alexandrovich Kryukov 30-Mar-11 15:24pm    
Agree, my 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900