Set specific bit in byte Set specific bit in byte java java

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, ormy_byte |= 1 << pos;              // shorthand

To un-set a bit, or turn it to 0:

my_byte = my_byte & ~(1 << pos);  // longer version, ormy_byte &= ~(1 << pos);           // shorthand

For examples, see Advanced Java/Bitwise Operators


To set a bit:

myByte |= 1 << bit;

To clear it:

myByte &= ~(1 << bit);


Just to complement Jon‘s answer and driis‘ answer

To toggle (invert) a bit

    myByte ^= 1 << bit;