Writing C readable bitfield structs?

John Machin sjmachin at lexicon.net
Thu Mar 17 18:56:35 EST 2005


phark52 at yahoo.com TOP-POSTED:
> Anyone have any idea?

1. Larry Bates has already told you.

2. I note that you say "I do not want to use a new int for every member
of struct S.", *not* "I am forced to pack bools into an int, 1 bit per
bool, because I have no control over the file format". Quite a
difference.

3. One could ask: How you would do it in your C app, if C didn't have
bitfields in structs?

Never mind, I'll give a bit more detail:

In your Python script:

!APOS = 0; BPOS = 1; CPOS = 2
!for each record: # pseudocode
!   outint = 0
!   if is_a: outint |= (1 << APOS)
!   if is_b: outint |= (1 << BPOS)
!   if is_c: outint |= (1 << CPOS)
!   etc

Note that AFAIK, C makes no guarantee about the order of bitfields in
structs, nor whether they start at the big end or the little end of the
int that contains them; so you may need to change the APOS etc numbers.

If you do have control over your C app, you could use the struct module
to pack the bools one per byte, and remove any concerns about the
idiosyncracies of C compilers and the endianness of the source and
target architectures. You could even make the file not only eyeballable
but robust by representing the values as "T" and "F" instead of "\1"
and "\0" (recalling that by ancient tradition C programs are likely to
stuff up mightily when presented with "\0" in data).




More information about the Python-list mailing list