0

what i am trying to accomplish is

user enters bit field widths, say 17 5 8 19 0 (can be more or less bit fields) 0 states end of bit field inputs

then user enters in values to be stored in a allocated array set to the bit field sizes.
say 1 2 3 4

how do i scan in several bit field values to be put in a struct like this?

struct{
    unsigned int bit0:1;
    unsigned int bit1:1;
    unsigned int bit2:1;
    unsigned int bit3:1;
}pack;

Then would this be correct when setting up the array to bit field size? I'm using "bit field inputs" in place of however i would scan them in for now.

pack = (int *)malloc(sizeof(struct)*bit field inputs);

i believe i asked my original question wrong, what im trying to do here is take say value 1 and put it in to a bit field width say 17 and keep repeating this for up to 5 values.

if the user inputs the bit field widths how would i take value one and store it in a field width of 17?

2 Answers2

2

If you need dynamic bit field widths, you need to do your own bit-fiddling. For compatibility, you should do it anyway.
If not, you must read it into a standard type like int and then asign to the bitfield, so the compiler does your bitpacking for you. But beware, the standard gives few guarantees regarding the compilers choices in this.

Also, never cast the return value of malloc: Do I cast the result of malloc?.

Community
  • 1
  • 1
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • How would i do the dynamic bit field widths? – Trying to program Apr 18 '14 at 20:27
  • You need to use bit shifting and other bitwise operations for that, just remember to use unsigned types. If you cannot get something going, search this site for extracting / replacing / inserting bit strings. – Deduplicator Apr 18 '14 at 20:31
1

It is up to the compiler to determine the order and padding for bitfields. There are no guarantees.

In general, you should only use bitfields "internally" in your program. Anytime you serialize bitfields, you may run into incompatibilities.

You would generally be better off by serializing into a structure with known size and alignment, then explicitly copying the values into your bitfield to use internally.

After re-reading your question again, I think you would be better off using bit-masking operations on contiguous bytes. This allows you to control the memory layout of your internal representation.

It sounds like you want to:

  1. read and store the bit offsets from the input string
  2. sum up how many bits the user wants to use from their input string
  3. malloc some bytes of contiguous memory that is large enough to contain the user bits
  4. provide accessor functions to the bit position and length of data, then use masking to set the bits.

Or if you don't care about size, just make everything an array of unsigned ints and let the compiler do the alignment for you.

Josh Petitt
  • 9,371
  • 12
  • 56
  • 104