-2

Maybe there is an answer for this but i couldn't find one i understand, so forgive me.

Say you have a variable with an unsigned int (32-bits) foo which i want to use for storing values in. As an example i want to store the values 1 and 4 inside the unsigned int as flags which makes the corresponding binary places to 1. foo would then look like all zeros until the last eight bits where it would be 0001 0010 (where the rightmost 0 represents the value 0). How do i do this using bitmanipulation?

2 Answers2

2

Something like this:

unsigned int const flag_one  = 0x02;  // 0000 0010
unsigned int const flag_four = 0x10;  // 0001 0000

unsigned int myflag = flag_one | flag_four;

// to test:
if (myflag & flag_one) { /* flag one is set */ }

// to set:
your_flag |= flag_four;     //  ORs with 0001 0000

// to clear:
their_flag &= ~flag_four;   // ANDs with 1110 1111
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

If you want to mark specific places, just use a bitshift. Here's a small example:

void setflag(int * flag, int place)
{
    // Or sets it to true if it's 0 or 1
    *flag |= (1 << place);
}
int main(int argc, char const *argv[])
{
    int flag = 0;

    setflag(&flag, 1);
    setflag(&flag, 4);

    printf("Flag is now %d\n", flag);
    return 0;
}

Output:

Flag is now 18

18 in binary is 10010, so that meets you criteria.

ozdrgnaDiies
  • 1,909
  • 1
  • 19
  • 34