32

How to set/unset a bit at specific position of a long in Java ?

For example,

long l = 0b001100L ; // bit representation

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 ?

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
Arpssss
  • 3,850
  • 6
  • 36
  • 80

5 Answers5

78

To set a bit, use:

x |= 0b1; // set LSB bit
x |= 0b10; // set 2nd bit from LSB

to erase a bit use:

x &= ~0b1; // unset LSB bit (if set)
x &= ~0b10; // unset 2nd bit from LSB

to toggle a bit use:

x ^= 0b1;

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 << 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

Or to toggle:

x ^= (1 << y) | (1 << z); // toggle yth and zth bit
nook
  • 2,378
  • 5
  • 34
  • 54
ronalchn
  • 12,225
  • 10
  • 51
  • 61
9

The least significant bit (lsb) is usually referred to as bit 0, so your 'position 2' is really 'bit 1'.

long x = 0b001100;  // x now = 0b001100
x |= (1<<1);        // x now = 0b001110 (bit 1 set)
x &= ~(1<<2);       // x now = 0b001010 (bit 2 cleared)
push2eject
  • 203
  • 2
  • 6
3

I would choose BigInteger for this...

class Test {
    public static void main(String[] args) throws Exception {
        Long value = 12L;
        BigInteger b = new BigInteger(String.valueOf(value));
        System.out.println(b.toString(2) + " " + value);
        b = b.setBit(1);
        b = b.clearBit(2);
        value = Long.valueOf(b.toString());
        System.out.println(b.toString(2) + " " + value);
    }
}

and here is the output:

1100 12
1010 10
Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
  • 7
    Don't use BigInteger. It was not designed for manipulating bits (slow?!?). If you want an arbitrarily length bit container, use bitsets. – ronalchn Aug 18 '12 at 04:28
0

Please see the class java.util.BitSet that do the job for you.

To set : myByte.set(bit); To reset : myByte.clear(bit); To fill with a bool : myByte.set(bit, b); To get the bool : b = myByte.get(bit);

sebyku
  • 149
  • 2
  • 3
-1
  • Convert long to a bitset
  • Set the bit you need to
  • Convert bitset back to long

See this post BitSet to and from integer/long for methods to convert long to bitset and vice versa

Community
  • 1
  • 1
Kan
  • 9
  • 2
    Using bitsets can work, but I don't recommend converting back and forth just for bit manipulation. Decide if you want to use long or bitset, and stick with it. – ronalchn Aug 18 '12 at 04:02