I'm trying to set bits in Java byte variable. It does provide propper methods like .setBit(i)
. Does anybody know how I can realize this?
I can iterate bit-wise through a given byte:
if( (my_byte & (1 << i)) == 0 ){ }
However I cannot set this position to 1 or 0, can I?
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.
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).
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.
Use the bitwise OR (|
) and AND (&
) operators. To set a bit, namely turn the bit at pos
to 1
:
my_byte = my_byte | (1 << pos); // longer version, or my_byte |= 1 << pos; // shorthand
To un-set a bit, or turn it to 0
:
my_byte = my_byte & ~(1 << pos); // longer version, or my_byte &= ~(1 << pos); // shorthand
For examples, see Advanced Java/Bitwise Operators
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