making a bit field
Mar 5, 2008 at 4:51pm UTC
For this project the upper nybble is level and lower nybble is observation data.
Upper nybble
Bits for upper level, middle level, lower level, vertically developed.
Lower nybble
(bool) nimbus?, (bool) did rain actually fall?
(bool) observed during day? (sunrise to sunset)
(bool) observed during night? (sunset to sunrise)
When writing my bit field, do I put the upper first?
1 2 3 4 5 6 7 8 9 10
struct cloud {
unsigned lowerlevel:1;
unsigned midlevel:1;
unsigned highlevel:1;
unsigned vertdev:1;
unsigned nimbus:1;
unsigned rainfall:1;
unsigned risetoset:1;
unsigned settorise:1;
};
Do I put lower first?
1 2 3 4 5 6 7 8 9 10
struct cloud {
unsigned settorise:1;
unsigned risetoset:1;
unsigned rainfall:1;
unsigned nimbus:1;
unsigned vertdev:1;
unsigned highlevel:1;
unsigned midlevel:1;
unsigned highlevel:1;
};
Hotaru
Mar 5, 2008 at 10:00pm UTC
Unfortunately, the answer is that it is compiler and machine dependent which order the bits are packed.
In general, you really don't save much code by using bitfields over code that specifically handles your data type.
If you are using C++, a simple class should do it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
class cloud {
unsigned char f_data;
bool manipbit( int b, int i ) {
unsigned char mask = 1 << i;
if (b >= 0) {
f_data &= ~mask;
f_data |= b << i;
}
return (f_data & mask);
}
public :
cloud(): f_data( 0 ) {}
bool lowerlevel() { return manipbit( -1, 7 ); }
cloud &lowerlevel( bool b ) { manipbit( b, 7 ); return *this ; }
bool midlevel() { return manipbit( -1, 6 ); }
cloud &midlevel( bool b ) { manipbit( b, 6 ); return *this ; }
...
bool settorise() { return manipbit( -1, 0 ); }
cloud &settorise( bool b ) { manipbit( b, 0 ); return *this ; }
};
The size of this whole class is, you guessed it, one byte. But you can use it handily to toggle specific, individual bits.
1 2 3 4
cloud nimbus;
nimbus.nimbus( true ).rainfall( true );
cout << "Lower level is " << nimbus.lowerlevel() << end;
cout << "Nimbus is " << nimbus.nimbus() << endl;
Hope this helps.
[EDIT] Made better inline methods...
Last edited on Mar 6, 2008 at 12:23am UTC
Topic archived. No new replies allowed.