using BitMask:- PLZ URGENT
hey guys,
there is a service and 6 modules r running under this service. now in my class i have to maintain a list of these modules and assign true or false to these modules and when asked for the state of a module, should be able to print which module is true and which is false.
Example:
the six modules r:
1) event
2)server
3)client
4)base
5)currrent
6)previous.
in my class:
public boolean event = true;
public boolean server = true;
public boolean cleint = true;
public boolean base = true;
public boolean current = true;
public boolean previous = true;
can i do this using bitmask? Do i make sense?
Yes.
class Services {
public static final int EVENT = 1;
public static final int SERVER = 2;
public static final int CLIENT = 4;
public static final int BASE = 8;
public static final int CURRENT = 16;
public static final int PREVIOUS = 32;
public int state;
}
Services s;
s.state |= EVENT;// set EVENT flag
s.state &= ~SERVER; // clear SERVER flag
s.state ^= CLIENT;// toggle CLIENT flag
if (s.state & s.BASE) // test BASE flag
Which part is unclear? Steve gave you a way to define the flags and ways to modify a variable using them (setting, clearing and toggling). You can do what ever you want!
Wrapping methods around those operations might be a good idea...
public void setFlag(int flag) {
state |= flag;
}
public void clearFlag(int flag) {
state &= ~flag;
}
public void setEvent(boolean b) {
if (b) setFlag(EVENT);
else clearFlag(EVENT);
}
public boolean isEventSet() {
return ((state & EVENT) != 0);
}
By the way, there's a small bug in the code:if (s.state & s.BASE != 0) // test BASE flag
Arg! There's my C background showing!
Actually, it should be
if ((s.state & s.BASE) != 0) // test BASE flag
Because the precedence of != is higher than that of &, exactly as it is in C and C++.
If you tell us which part you don't understand, we can explain that part. If you simply say that you don't understand, we don't know which part to explain.
Do you not know about binary or hex represntation?
Do you not understand bitwise operators?
Do you not understand how bits represent flags?
Something else?