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 ?
To set a bit, use:
to erase a bit use:
to toggle a bit use:
Notice I use 0b?. You can also use any integer, eg:
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:
(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:
Or to unset:
Or to toggle: