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