Java Working with bits

James picture James · Oct 27, 2010 · Viewed 26.3k times · Source

Let me start by saying I have never really worked with bits before in programming. I have an object that can be in 3 states and I want to represent those states using a 3 bit array.
For example:

I have a race car and it can go forward,left, and right at a stand still the bits would be 000
If the car was moving forward the bits would be 010 if forward and left it would be 110 etc...

How would I set the bits and how could I read them back to get the values?

Answer

Emil picture Emil · Oct 27, 2010

I would suggest using BitSet along with enum's

enum State { LEFT, RIGHT, FORWARD,STAND_STILL}

BitSet stat=new BitSet(4);

void setLeft() // and so on for each state
{
 stat.set(State.LEFT);
}
boolean isLeft()
{
 stat.get(State.LEFT);
}
void reset() //reset function to reset the state
{
  stat.clear();
}