ansi - Representing individual bits in C -


if have 16 bits represent 3 pairs of values, each 5 bits long, , 1 other 1 bit value, in order, safe use bitfield describe this? ansi c guarantee bits in order specify?

struct {     unsigned v1 : 5;     unsigned v2 : 5;     unsigned v3 : 5;     unsigned v4 : 1; } test; 

if not, there other data structure can use represent this? or should store 2 8 bit chars , manipulate them programmatically assured of portability?

the relevant quote find 6.7.2.1(1), c99:

an implementation may allocate addressable storage unit large enough hold bit- field. if enough space remains, bit-field follows bit-field in structure shall packed adjacent bits of same unit. if insufficient space remains, whether bit-field not fit put next unit or overlaps adjacent units implementation-defined. order of allocation of bit-fields within unit (high-order low-order or low-order high-order) implementation-defined. alignment of addressable storage unit unspecified.

i think unsigned isn't "underlying unit" type, rather, it's part of bitfield declaration itself: t : n means "take n bits of type t". real question whether implementation required pick "large" unit. example, use three bytes making unit char; 1 v1, 1 v2, , last 1 v3, v4. or make unit 16-bit integer, in case required use 1 single unit.

as noted, though, ordering of bit fields within unit unspecified. atomic unit of data in c address, , bitfields don't have addresses. it's guaranteed address of struct members increases in order of declaration, cannot make such statement bitfields (only underlying units).


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -