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:
1 2 3 4 5 6 7 8 9 10 11 12
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
}
}
}
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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
}
}
I'm guessing that each bit will require us to do something different, so a loop doesn't really help us:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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:
1 2 3 4 5 6 7 8 9 10 11 12
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