如何从一个字节中获取某个位置的某个位的值?
如果我有一个字节,该方法将如何检索某个位置的位?
这是我所知道的,但我认为这不起作用。
public byte getBit(int position) {
return (byte) (ID >> (position - 1));
}
其中 ID
是我从中检索信息的字节的名称。
If I have a byte, how would the method look to retrieve a bit at a certain position?
Here is what I have know, and I don't think it works.
public byte getBit(int position) {
return (byte) (ID >> (position - 1));
}
where ID
is the name of the byte I am retrieving information from.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
按位置右移 ID 将使位 #position 位于数字中最右边的位置。将其与 1 的按位 AND
&
结合起来将告诉您该位是否已设置。Right shifting ID by position will make bit #position be in the furthest spot to the right in the number. Combining that with the bitwise AND
&
with 1 will tell you if the bit is set.您想要制作一个位掩码并进行按位与。这最终看起来非常接近你所拥有的——使用shift设置适当的位,使用
&
进行按位运算。因此,
pos
的范围必须在 0 到 7 之间。如果您的最低有效位为“位 1”,那么您需要-1
,但我建议不要这样做——这种立场的改变对我来说总是错误的根源。You want to make a bit mask and do bitwise and. That will end up looking very close to what you have -- use shift to set the appropriate bit, use
&
to do a bitwise op.So
where
pos
has to range between 0 and 7. If you have the least significant bit as "bit 1" then you need your-1
but I'd recommend against it -- that kind of change of position is always a source of errors for me.获取整数的第 n 位
to get the nth bit in integer
在Java中,以下工作正常:
value
和x
可以是int
或long
(并且不需要是一样的)。非 Java 程序员的警告:前面的表达式在 Java 中有效,因为在该语言中,位移运算符仅适用于 5(或 6,如果是
long
) 右侧操作数的最低位。这隐式地将表达式转换为value << (~x & 31)
(或value << (~x & 63)
如果value
为long
)。Javascript:它也适用于 javascript(与 java 一样,仅应用移位计数的最低 5 位)。在 javascript 中,任何
数字
都是 32 位的。特别是在 C 中,负移位计数会调用未定义的行为,因此此测试不一定有效(尽管可能有效,具体取决于编译器/处理器的特定组合)。
In Java the following works fine:
value
andx
can beint
orlong
(and don't need to be the same).Word of caution for non-Java programmers: the preceding expression works in Java because in that language the bit shift operators apply only to the 5 (or 6, in case of
long
) lowest bits of the right hand side operand. This implicitly translates the expression tovalue << (~x & 31)
(orvalue << (~x & 63)
ifvalue
islong
).Javascript: it also works in javascript (like java, only the lowest 5 bits of shift count are applied). In javascript any
number
is 32-bit.Particularly in C, negative shift count invokes undefined behavior, so this test won't necessarily work (though it may, depending on your particular combination of compiler/processor).
要获取任意位置的位,只需执行以下步骤:
在数字 5 中,位置是从右到左(由索引给出)
数字 (5) = |0|1|0|1|
位置 = |3|2|1|0|
现在您想要获取第 3 个位置(索引 = 2)的位,
即:
您可以返回 true 或 false,如下所示:
To get the bit at any position, simply do the following steps:
In the number 5, the positions are from right to left (as given by index)
Number (5) = |0|1|0|1|
Positions = |3|2|1|0|
Now you want to get the bit at position 3rd (index = 2)
i.e:
you can return true or false like: