Set specific bit in byte



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?


Posted 2011-01-12T21:00:05.693

Reputation: 2 709



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 << bit;`             // shorthand

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

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

For examples, see Advanced Java/Bitwise Operators


Posted 2011-01-12T21:00:05.693

Reputation: 120 404

3see also the xor operator -- it's the third power-tool in that arsenal (see the Wikipedia article on masking). – Hardryv – 2012-03-29T17:35:58.570


To set a bit:

myByte |= 1 << bit;

To clear it:

myByte &= ~(1 << bit);

Jon Skeet

Posted 2011-01-12T21:00:05.693

Reputation: 1 070 456

what do you mean this would "set" a bit? say you were trying to access the 0th bit, and myByte contains 11101101. What does this mean? How do I control what the value being set is? – Michael – 2016-03-06T05:08:40.043

4@Michael: Setting a bit means making it 1. Clearing a bit means making it 0. – Jon Skeet – 2016-03-06T08:50:00.097


Just to complement Jon‘s answer and driis‘ answer

To toggle (invert) a bit

    myByte ^= 1 << bit;

Carlos Heuberger

Posted 2011-01-12T21:00:05.693

Reputation: 23 793

this is cleaner than two separate operations... – ernesto – 2015-03-17T16:46:14.323

1@ernesto but it does not specifically answer the question. He asked how to set the bit, not toggle it. There is a difference. Of course, you could check the bit first, then toggle it if needed, but that would be 2 separate tasks as well... – Justin Smith – 2016-05-27T22:50:06.953


The technique you need is to isolate the chosen bit and either set or clear it. You already have the expression to isolate the bit since you're using that to test it above. You can set the bit by ORing it in, or clear the bit by bitwise AND with the 1's complement of the bit.

boolean setBit;
my_byte = setBit
          ? myByte | (1 << i)
          : myByte & ~(1 << i);

Jeffrey Hantin

Posted 2011-01-12T21:00:05.693

Reputation: 29 150


Please see the class java.util.BitSet that do the job for you.

To set : myByte.set(bit); To reset : myByte.clear(bit); To fill with a bool : myByte.set(bit, b); To get the bool : b = myByte.get(bit); Get the bitmap : byte bitMap = myByte.toByteArray()[0];


Posted 2011-01-12T21:00:05.693

Reputation: 69

3Careful with bitset. There is no distinction between setting a bit to 0 and clearing it, thus length() would not count those bits set to 0 – Alex – 2015-10-13T09:28:31.193