首先,我要说我在编程之前从未真正使用过位。我有一个可以处于3种状态的对象,我想使用3位数组表示这些状态。例如:我有一辆赛车,它可以在架子上向前,向左和向右行驶,位会是000如果汽车向前行驶,那么向前和向左的位将为010,以此类推...如何设置位,如何读回它们以获取值?
如果大小和速度很重要,请使用字节中的位。 (请阅读其他答案中发布的链接,因为在使用和强制转换带符号的数据类型时会出现明显的并发症。)
这编码速度:站立,左,左向前,向前,向右和向右。
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();
}
}
输出:
3: Going forward turning left
5: Going forward turning right
7: Going forward turning right turning left (conflicting)
3: Going forward turning left
还要注意,左和右是互斥的,因此有可能创建非法组合。 (7 = 111)
如果您实际上是说事物只能向左,向前或向右移动,那么您不需要标记,只需要枚举即可。
该枚举只能在两位中传输。
enum Direction{
NONE, FORWARD, RIGHT, LEFT;
}
Direction dir = Direction.FORWARD;
byte enc = (byte) dir.ordinal();
enc
中的最后两位将变为:
00 : none
01 : forward;
10 : right
11 : left
我建议与枚举一起使用[C0
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();
}
。
阅读按位运算符的byte
以开始使用。
编辑:位掩码上的this tutorial也可能非常有帮助。
在java.util中,有一个名为enum State { FORWARD, FORWARD_LEFT, FORWARD_RIGHT, STAND_STILL }
的类,它使位操作非常简单。
在您的情况下,您可以创建大小为3的BitSet,然后使用get()和set()方法设置对位的检查。