Java使用位

Mag*_*ero 13 java bits bitmask

首先让我说在编程之前我从未真正使用过bit.我有一个可以处于3种状态的对象,我希望使用3位数组来表示这些状态.
例如:

我有一辆赛车,它可以前进,左,右站在一个站点上,比特将是000
如果汽车向前移动,如果向前,那么位将是010,如果向前,它将是110等...

我如何设置这些位,如何读取它们以获取值?

Emi*_*mil 10

我建议使用BitSet和枚举

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();
}
Run Code Online (Sandbox Code Playgroud)


Kar*_*rlP 9

如果大小和速度很重要,请使用字节中的位.(阅读其他答案中发布的链接,因为在使用和转换签名数据类型时存在非明显的复杂性.)

这对速度进行编码:stand,left,left_forward,forward,right_forward和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();
}

}
Run Code Online (Sandbox Code Playgroud)

输出:

3: Going forward turning left 
5: Going forward turning right 
7: Going forward turning right turning left  (conflicting)
3: Going forward turning left 
Run Code Online (Sandbox Code Playgroud)

另请注意,Left和Right是互斥的,因此可能会创建非法组合.(7 = 111)

如果你实际上意味着一件东西只能移动LEFT,FORWARD或RIGHT,那么你就不需要旗帜,只需要枚举.

该枚举可以仅以两位传输.

    enum Direction{
    NONE, FORWARD, RIGHT, LEFT;

}


Direction dir = Direction.FORWARD;
byte enc = (byte) dir.ordinal();
Run Code Online (Sandbox Code Playgroud)

最后两位enc将成为:

00 : none  
01 : forward;
10 : right
11 : left
Run Code Online (Sandbox Code Playgroud)