What method would you use to determine if the the bit that represents 2^x is a 1 or 0 ?
I'd use:
if ((value & (1L << x)) != 0)
{
// The bit was set
}
(You may be able to get away with fewer brackets, but I never remember the precedence of bitwise operations.)
-
53
-
12
-
4@ThibThib nothing strange about it. Please don't post stupid anti Java flame bait. – amischiefr Jul 7 '09 at 14:04
-
12I wonder if ((value>>>x) & 1) != 0 is better because it doesn't matter whether value is long or not, or if its worse because it's less obvious. – Tom Hawtin - tackline Jul 7 '09 at 14:16
-
4@ArtOfWarfare: I've sometimes mistyped
==
as=
- which leads to a valid expression assigning that value, which is not what I want. In Java, that's illegal (assuming it's not aboolean
variable). Bitwise operators are part of Java, and that's a good thing IMO. There are plenty of situations where you want bitwise operators. There's no need to conflate that with whether or not the type of a condition expression inwhile
,if
etc should beboolean
- which I believe it should. – Jon Skeet Nov 28 '13 at 18:35
Another alternative:
if (BigInteger.valueOf(value).testBit(x)) {
// ...
}
-
41
-
9Not a very good solution if this code is going to be called often. You're replacing a one-line alternative with a one line alternative, and the bit shifts really aren't that hard. – wds Aug 28 '09 at 7:32
-
3Length of line != readability of line, wds. You might be right that the previous solution is more efficient, but the difference is likely marginal, especially if testBit() gets inlined. – WCWedin Aug 29 '09 at 16:05
-
7It should be noted this solution allocates memory and is much less efficient than bitwise operators. Yes, it often doesn't matter, but sometimes it is important to avoid unnecessary GC and/or inefficient code (Android apps, in a game's main loop, etc). – NateS Oct 28 '10 at 5:16
-
6Resource waste. If you can't trust the "future maintainers" for understanding bit operations then you have a bigger problem than that with human resources on the project. Bit operations isn't magic. This is part of the basic set of a programmer skills. – dolmen May 6 '13 at 15:32
I wonder if:
if (((value >>> x) & 1) != 0) {
}
.. is better because it doesn't matter whether value is long or not, or if its worse because it's less obvious.
Tom Hawtin - tackline Jul 7 at 14:16
-
I think it's better because there is less potential for errors - and if you think it isn't obvious, you can always extract the test into an appropriately named function (boolean isBitSet(long value, int x) or so) – hjhill Aug 26 '09 at 8:30
You can also use
bool isSet = ((value>>x) & 1) != 0;
EDIT: the difference between "(value>>x) & 1
" and "value & (1<<x)
" relies on the behavior when x is greater than the size of the type of "value" (32 in your case).
In that particular case, with "(value>>x) & 1
" you will have the sign of value, whereas you get a 0 with "value & (1<<x)
" (it is sometimes useful to get the bit sign if x is too large).
If you prefer to have a 0 in that case, you can use the ">>>
" operator, instead if ">>
"
So, "((value>>>x) & 1) != 0
" and "(value & (1<<x)) != 0
" are completely equivalent
For the n
th LSB (least significant bit), the following should work:
boolean isSet = (value & (1 << n)) != 0;
-
8
You might want to check out BitSet: http://java.sun.com/javase/6/docs/api/java/util/BitSet.html
In Java the following works fine:
if (value << ~x < 0) {
// xth bit set
} else {
// xth bit not set
}
value
and x
can be int
or long
(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 to value << (~x & 31)
(or value << (~x & 63)
if value
is long
).
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).
The value of the 2^x bit is "variable & (1 << x)"
-
As Matt Kane said in identical solutions: That should be 1L, or (1 << 32) ends up with the same value as (1 << 0) – drvdijk Jul 7 '09 at 13:59
If someone is not very comfortable with bitwise operators, then below code can be tried to programatically decide it. There are two ways.
1) Use java language functionality to get the binary format string and then check character at specific position
2) Keep dividing by 2 and decide the bit value at certain position.
public static void main(String[] args) {
Integer n =1000;
String binaryFormat = Integer.toString(n, 2);
int binaryFormatLength = binaryFormat.length();
System.out.println("binaryFormat="+binaryFormat);
for(int i = 1;i<10;i++){
System.out.println("isBitSet("+n+","+i+")"+isBitSet(n,i));
System.out.println((binaryFormatLength>=i && binaryFormat.charAt(binaryFormatLength-i)=='1'));
}
}
public static boolean isBitSet(int number, int position){
int currPos =1;
int temp = number;
while(number!=0 && currPos<= position){
if(temp%2 == 1 && currPos == position)
return true;
else{
temp = temp/2;
currPos ++;
}
}
return false;
}
Output
binaryFormat=1111101000
isBitSet(1000,1)false
false
isBitSet(1000,2)false
false
isBitSet(1000,3)false
false
isBitSet(1000,4)true
true
isBitSet(1000,5)false
false
isBitSet(1000,6)true
true
isBitSet(1000,7)true
true
isBitSet(1000,8)true
true
isBitSet(1000,9)true
true
-
2One division costs about a hundred time more CPU time than a bit operator. And you do it iteratively. This 'solution' is on the level of BigInteger regarding performance. – Agoston Horvath Feb 9 '16 at 9:15
declare a temp int and make it equal the original. then shift temp >> x times, so that the bit you want to check is at the last position. then do temp & 0xf to drop the preceding bits. Now left with last bit. Finally do if (y & 1 == 0), if last bit is a 1, that should equal 0, else will equal 1. Its either that or if (y+0x1 == 0)... not too sure. fool around and see
-
2Why did you post a convoluted, hard to read, iffy answer that has nothing on the existing answers with 50+ upvotes? – Keith Pinson Dec 17 '12 at 19:05
My contribution - ignore previous one
public class TestBits {
public static void main(String[] args) {
byte bit1 = 0b00000001;
byte bit2 = 0b00000010;
byte bit3 = 0b00000100;
byte bit4 = 0b00001000;
byte bit5 = 0b00010000;
byte bit6 = 0b00100000;
byte bit7 = 0b01000000;
byte myValue = 9; // any value
if (((myValue >>> 3) & bit1 ) != 0) { // shift 3 to test bit4
System.out.println(" ON ");
}
}
}
I coded a little static class which is doing some of the bit operation stuff.
public final class Bitfield {
private Bitfield() {}
// ********************************************************************
// * TEST
// ********************************************************************
public static boolean testBit(final int pos, final int bitfield) {
return (bitfield & (1 << pos)) == (1 << pos);
}
public static boolean testNum(final int num, final int bitfield) {
return (bitfield & num) == num;
}
// ********************************************************************
// * SET
// ********************************************************************
public static int setBit(final int pos, final int bitfield) {
return bitfield | (1 << pos);
}
public static int addNum(final int number, final int bitfield) {
return bitfield | number;
}
// ********************************************************************
// * CLEAR
// ********************************************************************
public static int clearBit(final int pos, final int bitfield) {
return bitfield ^ (1 << pos);
}
public static int clearNum(final int num, final int bitfield) {
return bitfield ^ num;
}
}
If there are some questions flying around, just write me an email.
Good Programming!
Eliminate the bitshifting and its intricacies and use a LUT for the right and
operand.
-
This is considerably slower than a bitwise operation. It would require address lookups over a 1 or 2 clock cycle bitwise operation. – Kyle Falconer Mar 30 '15 at 17:43