Click to See Complete Forum and Search --> : bit field question


theperplepigg
August 2nd, 2002, 11:55 AM
i am working with bit fields in order to compress a large amount of information into a smaller amount to better fit in memory for an embedded system. i have never worked with bit fields before, though. the main reason for doing this is all the data is binary, and i find it wasteful to use a full byte in memory for a boolean value (i doubt i'm the only one), though i see the use of it for general purposes (like addressing). my question is whether or not it is legal to make an array inside a struct of bitfields, to make them accessable from a loop, and if it is legal, how is this achieved. consider the following structure :

typedef struct {
bool value[39];
} input;

is there a way to make the above array but with each boolean value being a single bit? i am unsure, since i realize pointers aren't allowed, but perhaps there is some way to do it still that i don't know about. (i have tried putting a :1 after the bool definition; of course it reaffirms that pointers aren't allowed)

--paul

stober
August 2nd, 2002, 12:40 PM
Here is one way:


unsigned short bits = 6;
for(int i = -1; i < 8; i++)
{
// get a power of 2
int one_bit = (i < 0) ? 1 : 2 << i;
if(bits & one_bit)
{
// Found one!
}
}

cup
August 2nd, 2002, 01:30 PM
I'm not sure about this but I think vector<bool> will pack the bools on some compilers.

Kdr Kane
August 2nd, 2002, 02:31 PM
I can't answer your question about arrays of bits.

Have you thought of using bit masks (AND) or bit shifts (<<)? This is typically the method used in assembly language.

It seems possible that the compiler could actually bloat your code more if you used arrays.

cup
August 2nd, 2002, 02:41 PM
Kdr Kane is right - I'd completely forgotten about this. Used to do it all the time in X windows.

Say you want n bools

unsigned int array[(n - 1) / _INTEGERAL_MAX_BITS + 1];

_INTEGRAL_MAX_BITS is a MS thing but there will probably be something on your system.

To set entry s

array[s/_INTEGRAL_MAX_BITS] |= (1 << (s % _INTEGRAL_MAX_BITS));

To clear entry s
array[s/_INTEGRAL_MAX_BITS] &= ~(1 << (s % _INTEGRAL_MAX_BITS));

To check entry s

bool set = array[s/_INTEGRAL_MAX_BITS] & (1 << (s % _INTEGRAL_MAX_BITS)) != 0;

theperplepigg
August 2nd, 2002, 03:34 PM
thanks, everyone for your comments, i will look at all the advice here and attempt to implement it over the next day or two (ok, that would start monday, not tomorrow :p) in the meantime...i gotta debug. cutting the size of the executable in half has it's ups AND downs...heh

--paul

cup
August 2nd, 2002, 04:43 PM
C++ also has bitset operations

bitset<39> value; // declares 39 bits

value.reset(i); // clears bit i

value.set(i); // sets bit i

value.test(i); // test bit i

Another alternative is to use the assembler

bts, btr and bt instructions