Check which flags are On/Off of an Integer Number?
javascript, jquery
Solution
You can't, as you already can see at the binary representation. A 3 can either be 3 or 2+1. So use powers of two:
0 // 0000
1 // 0001
2 // 0010
4 // 0100
8 // 1000
Then when examining a value of `5 (0101)`, you'll see the bits for 1 and 4 are set, so you know which flags were enabled.
I don't know the exact JavaScript syntax, but something like this will do:
FLAG_1 = 1
FLAG_2 = 2
FLAG_3 = 4
FLAG_4 = 8
FLAG_5 = 16
var foo = FLAG_2 | FLAG_5; // Use binary OR (|) to add flags
if (foo & FLAG_5)
{
// Do something that has to be done when FLAG_5 is set
}
Problem
First of all Sorry for my English. Let say I have, ``` 0 // 0 1 // 1 2 // 10 3 // 11 4 // 100 5 // 101 6 // 110 7...................... ``` Now, I can say that 5 has two(3rd and 1st) ON flags. Similarly, 7 has three(1st, 2nd and 3rd) ON flags and so on. Now, let say I have a input 2 and flag1, flag2, ..... flagn. I need to find pro-grammatically that only flag2 is ON.