Java 使用位
首先我要说的是,我以前从未在编程中真正使用过位。我有一个可以处于 3 种状态的对象,我想使用 3 位数组来表示这些状态。
例如:
我有一辆赛车,它可以向前、向左、向右行驶,静止时位将为 000
如果汽车向前移动,则位将为 010;如果向前并离开,则位将为 110 等等......
我将如何设置这些位以及如何读回它们以获取值?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我建议使用 BitSet 以及枚举
I would suggest using BitSet along with enum's
如果大小和速度很重要,请使用字节中的位。 (阅读其他答案中发布的链接,因为使用和转换签名数据类型时存在不明显的复杂性。)
这对速度进行编码:stand、left、left_forward、forward、right_forward 和 right。
输出:
另请注意,Left 和 Right 是互斥的,因此可能会创建非法组合。 (7 = 111 )
如果你实际上意味着一个东西只能向左、向前或向右移动,那么你不需要标志,只需要枚举。
该枚举只能以两位进行传输。
enc
中的最后两位将变为:If size and speed is important, use bits in a byte. (Read the links posted in the other answer as there are non-obvious complications when using and casting signed datatypes.)
This encodes for the speeds: stand, left, left_forward, forward, right_forward, and right.
Output:
Note also that Left and Right is mutually exclusive, so its possible to create an illegal combination. (7 = 111 )
If you actually meant that a thing can only move LEFT, FORWARD or RIGHT, then you don't need flags, just enums.
This enum is possible to transport in only two bits.
The final two bits in
enc
will become:存储这三位至少需要一个
字节
。请阅读有关按位运算符的本教程以开始使用。
编辑:此页面关于位掩码也可能非常有帮助。
The least you'll need to store these three bits is one
byte
.Read this tutorial on bitwise operators to get started.
Edit: this page on bit masks may also be very helpful.
你说的是三种状态,但实际上有六种:前进、左前、右前、左、右、静止。当然,除非你的赛车不侧向移动,否则你就有四辆。
您确实应该使用 enum 来实现此目的:
从左到右和forward 是互斥的,这对于一个需要摆弄的程序来说不太适合。你会遇到各种一致性问题。
You say three states, but you've actually got six: forward, forward-left, forward-right, left, right, stand-still. Unless your race car doesn't move sideways ofcourse, then you've got four.
You should really use an enum for this:
Since left, right and forward are mutually exclusive, this isn't a very good fit for a bit-fiddling program. You'll get into all kinds of consistency problems.
在java.util中有一个名为BitSet 这使得位操作变得非常简单。
在您的情况下,您可以创建一个大小为 3 的 BitSet,然后使用 get() 和 set() 方法来设置检查位。
In java.util there is a class called BitSet that makes bit manipulation very simple.
In your case you could create a BitSet of size 3 and then use the get() and set() methods to set a check the bits.