0

I apologize for being vague, but our teacher specifically told us to do so if we ask questions

I have 9 flags I want to store as an integer.
ie, 0b111111111 would be all of them tripped.

Right now I have an if statement adding to the int if it's tripped. ie.

if (flag0=="tripped" && flag0=="hasn't been tripped before") flagInt += 1;

if (flag1=="tripped" && flag1=="hasn't been tripped before") flagInt += 2;

if (flag2=="tripped" && flag2=="hasn't been tripped before") flagInt += 4;

and so on,

I'm having difficulty writing the code to check if a flag has been tripped or not. How could I do this?

edit: I've considered converting the integer to a string of it's binary representation, so I could just chck with brackets, but I have to do this for quite a bit of data, and that would make it too slow

David G
  • 94,763
  • 41
  • 167
  • 253
d0m1n1c
  • 157
  • 4
  • 16

1 Answers1

3

To get bit n state (returns bit n as 0 or 1):

(value>>n) & 1

To set bit n state (flag is 0 or 1):

value = (value & ~(1 << n)) | (flag << n)
mvp
  • 111,019
  • 13
  • 122
  • 148
  • bool play::used(int flag,int a){ int b = flag & a; if (flag == a) return true; return false; } thanks a lot, this is what I used. – d0m1n1c Sep 08 '13 at 01:18