86

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?

wishi
  • 7,188
  • 17
  • 64
  • 103

5 Answers5

159

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

driis
  • 161,458
  • 45
  • 265
  • 341
  • 3
    see also the xor operator -- it's the third power-tool in that arsenal (see the Wikipedia article on masking). – Hardryv Mar 29 '12 at 17:35
  • wow. this is actually basic computer science stuff but still mind blown me, binary world are awsome – elliotching Nov 05 '19 at 05:13
72

To set a bit:

myByte |= 1 << bit;

To clear it:

myByte &= ~(1 << bit);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    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 Mar 06 '16 at 05:08
  • 9
    @Michael: Setting a bit means making it 1. Clearing a bit means making it 0. – Jon Skeet Mar 06 '16 at 08:50
30

Just to complement Jon‘s answer and driis‘ answer

To toggle (invert) a bit

    myByte ^= 1 << bit;
Community
  • 1
  • 1
user85421
  • 28,957
  • 10
  • 64
  • 87
  • 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 May 27 '16 at 22:50
11

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
  • 35,734
  • 7
  • 75
  • 94
9

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

sebyku
  • 149
  • 2
  • 3
  • 3
    Careful 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 Oct 13 '15 at 09:28