bitfield?

hey gang,

i have a function in a library i'm trying to use. the function returns an int which is a bit field. i'd like to do a switch/case with the result in a loop to figure out what options are set, i.e. which bits are set.

the function returns a number like "128259" (as an int).

then i do something like this:

 ``123456789101112`` ``````result = getBitFiled(); for (i=0; i<15; i++) { if (result & i) { // this is where i'm not sure what to do switch(i) { case: 0x01 // do something // .... case: 0x100 // do something } } }``````

Any pointers?

thanks!

You can try something like this, but it's untested and my knowledge on bit fields is scarce, so you might want to wait for an answer from a more experienced person
 ``123456789101112131415`` ``````result = getBitFiled(); // 0 is the absence of flags for(i = 1; i <= last_flag_value; i << 1) { switch(result & i) { case 0: // The bit is turned off. It's the same as if(result & i == false) break; case 0x01: // or case OPTION_ONE break; case 0x02: break; // Etc } }``````
 ``12345678910111213`` ``````result = getBitFiled(); // 0 is the absence of flags for(i = 1; i <= last_flag_value; i << 1) { If(result & i) { //bit is set } else { //not set } }``````

The and will result in either 0 or 1 only.
Last edited on
I'm guessing that each bit will require us to do something different, so a loop doesn't really help us:
 ``1234567891011121314151617`` ``````result = getBitFiled(); if (result & 0x01) // do something if (result & 0x02) // do something if (result & 0x04) // do something if (result & 0x08) // do something if (result & 0x10) // do something if (result & 0x20) // do something if (result & 0x40) // do something if (result & 0x80) // do something ``````

I think there are occasions where loops are over-used. I've edited the following out of code I saw just the other day:
 ``123456789101112`` ``````for (int i = 0; i < 2; i++) { switch(i) { case 0: // do something break; case 1: // do something else break; } }`````` ```Edited result: // do something // do something else```
Topic archived. No new replies allowed.