Set specific bit in byte

wishi picture wishi · Jan 12, 2011 · Viewed 79.3k times · Source

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?

Answer

driis picture driis · Jan 12, 2011

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