如何设置警戒/解除警戒位在漫长的立场呢? [英] How to set/unset a bit at specific position of a long?
问题描述
如何设置警戒/解除警戒位为长期在Java中的特定位置?
How to set/unset a bit at specific position of a long in Java ?
例如,
long l = 0b001100L ; // bit representation
我要在位置2和取消位3位设置位从而相应的长会,
I want to set bit at position 2 and unset bit at position 3 thus corresponding long will be,
long l = 0b001010L ; // bit representation
任何人可以帮助我该怎么做?
Can anybody help me how to do that ?
推荐答案
要设置位,用途:
x |= 0b1; // set LSB bit
x |= 0b10; // set 2nd bit from LSB
要擦除位使用:
x &= ~0b1; // unset LSB bit (if set)
x &= ~0b10; // unset 2nd bit from LSB
切换了一下使用方法:
to toggle a bit use:
x ^= 0b1;
请注意我用0B?你也可以使用任意整数,例如:
Notice I use 0b?. You can also use any integer, eg:
x |= 4; // sets 3rd bit
x |= 0x4; // sets 3rd bit
x |= 0x10; // sets 9th bit
然而,这使得它更难知道哪些位被改变。
However, it makes it harder to know which bit is being changed.
使用二进制可以让你看到它的确切位将被设置/删除/切换。
Using binary allows you to see which exact bits will be set/erased/toggled.
要动态地设置位,用途:
To dynamically set at bit, use:
x |= (1 << y); // set the yth bit from the LSB
(1 LT;&LT; Y)。
的移动左... 001 y位,这样你就可以移动设置位y地方
(1 << y)
shifts the ...001 y places left, so you can move the set bit y places.
您也可以一次设定多个位:
You can also set multiple bits at once:
x |= (1 << y) | (1 << z); // set the yth and zth bit from the LSB
还是要取消设置:
Or to unset:
x &= ~((1 << y) | (1 << z)); // unset yth and zth bit
或切换:
x ^= (1 << y) | (1 << z); // toggle yth and zth bit
这篇关于如何设置警戒/解除警戒位在漫长的立场呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!