Set specific bit in byte

I am trying to set bits in a Java byte variable. It provides methods like .setBit(i) . Does anyone know how I can figure this out?

I can iterate bit by bit over a given byte:

 if( (my_byte & (1 << i)) == 0 ){ } 

However, I cannot set this position to 1 or 0, can I?

+73
java bit-manipulation byte
Jan 12 '11 at 21:00
source share
5 answers

Use the bitwise operators OR ( | ) and AND ( & ). To set the bit, namely, set the bit to pos 1 :

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

To clear a bit or set it to 0 :

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

For examples, see Advanced Java / Bitwise Operators.

+121
Jan 12 2018-11-11T00:
source share

To set the bit:

 myByte |= 1 << bit; 

To clear it:

 myByte &= ~(1 << bit); 
+61
Jan 12 2018-11-12T00:
source share

Just to complement John 's answer and driis's answer

To switch (invert) a bit

  myByte ^= 1 << bit; 
+23
Jan 13 '11 at 7:12
source share

The necessary technique is to isolate the selected bit and set or clear it. You already have an expression to isolate the bit, since you use this to check it above. You can set the bit by its OR, or clear the bit by bit AND with 1 complement bit.

 boolean setBit; my_byte = setBit ? myByte | (1 << i) : myByte & ~(1 << i); 
+10
Jan 12 2018-11-11T00:
source share

See the java.util.BitSet class that does this work for you.

To install: myByte.set(bit); For reset: myByte.clear(bit); Fill in bool: myByte.set(bit, b); To get bool: b = myByte.get(bit); Get a bitmap: byte bitMap = myByte.toByteArray()[0];

+7
May 22 '15 at 13:48
source share



All Articles