Set specific bit in byte

JavaByteBit Manipulation

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

To set a bit:

myByte |= 1 << bit;

To clear it:

myByte &= ~(1 << bit);

Solution 3 - Java

Just to complement [Jon‘s answer](https://stackoverflow.com/questions/4674006/set-specific-bit-in-byte/4674035#4674035 "") and [driis‘ answer](https://stackoverflow.com/questions/4674006/set-specific-bit-in-byte/4674055#4674055 "")

To toggle (invert) a bit

    myByte ^= 1 << bit;

Solution 4 - Java

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);

Solution 5 - Java

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];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwishiView Question on Stackoverflow
Solution 1 - JavadriisView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - Javauser85421View Answer on Stackoverflow
Solution 4 - JavaJeffrey HantinView Answer on Stackoverflow
Solution 5 - JavasebykuView Answer on Stackoverflow