Set specific bit in byte
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
To set a bit:
myByte |= 1 << bit;
To clear it:
myByte &= ~(1 << bit);