Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

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 standstill the bits would be 000

If the car was moving forward the bits would be 010 and left it would be 110 etc...

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

1 Answer

0 votes
by (13.1k points)

If the size and speed are important, use bits in a byte. This encodes for the speeds: stand, left, left_forward, right_forward, and right.

public class Moo {

final static byte FORWARD = 0x1; // 00000001

final static byte LEFT     =0x2; // 00000010

final static byte RIGHT    =0x4; // 00000100

/**

 * @param args

 */

public static void main(String[] args) {

    byte direction1 = FORWARD|LEFT;  // 00000011

    byte direction2 = FORWARD|RIGHT; // 00000101

    byte direction3 = FORWARD|RIGHT|LEFT; // 00000111

    byte direction4 = 0;

    // someting happens:

    direction4 |= FORWARD;

    // someting happens again.

    direction4 |= LEFT;

    System.out.printf("%x: %s\n", direction1, dirString(direction1));

    System.out.printf("%x: %s\n", direction2, dirString(direction2));

    System.out.printf("%x: %s\n", direction3, dirString(direction3));

    System.out.printf("%x: %s\n", direction4, dirString(direction4));


 

}

public static String dirString( byte direction) {

    StringBuilder b = new StringBuilder("Going ");

    if( (direction & FORWARD) > 0){

        b.append("forward ");

    }

    if( (direction & RIGHT) > 0){

        b.append("turning right ");

    }

    if( (direction & LEFT) > 0){

        b.append("turning left ");

    }

    if( (direction &( LEFT|RIGHT)) == (LEFT|RIGHT)){

        b.append(" (conflicting)");

    }

    return b.toString();

}

}

Output:

3: Going forward turning left 

5: Going forward turning right 

7: Going forward turning right turning left  (conflicting)

3: Going forward turning left 

Here you can see that left and right are mutually exclusive, so it is possible to create an illegal combination.

If you meant that a thing can only move LEFT, FORWARD, or RIGHT, then you don’t need flags, you need enums.

The enum is possible to transport in only two bits.

  enum Direction{

    NONE, FORWARD, RIGHT, LEFT;

}


 

Direction dir = Direction.FORWARD;

byte enc = (byte) dir.ordinal();

The final two bits in enc will become:

00 : none  

01 : forward;

10 : right

11 : left

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 14, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Apr 6, 2021 in Java by Jake (7k points)
0 votes
1 answer

Browse Categories

...