Set specific bit in byte

前端 未结 5 530
故里飘歌
故里飘歌 2020-11-30 19:29

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

5条回答
  •  死守一世寂寞
    2020-11-30 19:32

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

提交回复
热议问题