Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Working with bits

Tags:

java

bitmask

bits

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?

like image 734
James Andino Avatar asked Oct 27 '10 10:10

James Andino


People also ask

What are bits in Java?

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).

Can Java manipulate bit?

The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.

What is this >>> bitwise operator in Java?

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.

Why do we need bitwise operators in Java?

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.


1 Answers

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();
}
like image 67
Emil Avatar answered Sep 18 '22 02:09

Emil