Set specific bit in byte

前端 未结 5 527
故里飘歌
故里飘歌 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:47

    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

提交回复
热议问题