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?
Bits and BytesA bit is derived from the phrase “binary digit,” represented by 0 or 1. These two seemingly simple numbers can carry a lot of information when combined. The 0 basically means off/false and 1 means on/true. To put it colloquially, a switch can signal one of two things, either off (0) or on (1).
The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.
It is a binary operator denoted by the symbol ^ (pronounced as caret). It returns 0 if both bits are the same, else returns 1. Let's use the bitwise exclusive OR operator in a Java program.
Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With