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 ?
Use the bitwise AND operator (&) to clear a bit. number &= ~(1 << x); That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.
Setting a bitUse the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.
The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k'th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k'th bit which is 0.
To set any bit we use bitwise OR | operator. As we already know bitwise OR | operator evaluates each bit of the result to 1 if any of the operand's corresponding bit is set (1).
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With