如何从字节中获取某个位置的位值? [英] How to get the value of a bit at a certain position from a byte?
本文介绍了如何从字节中获取某个位置的位值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个字节,该方法将如何在某个位置取回一个比特?
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));
}
其中ID
是我要从中检索信息的字节的名称.
where ID
is the name of the byte I am retrieving information from.
推荐答案
public byte getBit(int position)
{
return (ID >> position) & 1;
}
按位置右移ID将使#position位在数字右侧最远的位置.将其与按位AND &
与1结合使用将告诉您是否设置了该位.
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.
position = 2
ID = 5 = 0000 0101 (in binary)
ID >> position = 0000 0001
0000 0001 & 0000 0001( 1 in binary ) = 1, because the furthest right bit is set.
这篇关于如何从字节中获取某个位置的位值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文