I have some data in field type Byte ( I save eight inputs in Byte, every bit is one input ). How to change just one input in that field ( Byte) but not to lose information about others ( example change seventh bit to one, or change sixth bit to zero )?
To set the seventh bit to 1:
b = (byte) (b | (1 << 6));
To set the sixth bit to zero:
b = (byte) (b & ~(1 << 5));
(The bit positions are effectively 0-based, so that's why the "seventh bit" maps to 1 << 6
instead of 1 << 7
.)
Declare b
as the primitive type byte
:
byte b = ...;
Then you can use the compound assignment operators that combine binary operations and assignment (this doesn't work on Byte
):
b |= (1 << bitIndex); // set a bit to 1
b &= ~(1 << bitIndex); // set a bit to 0
Without the assignment operator you would need a cast, because the result of the |
and &
operations is an int
:
b = (byte) (b | (1 << bitIndex));
b = (byte) (b & ~(1 << bitIndex));
The cast is implicit in the compound assignment operators, see the Java Language Specification.
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