Change bits value in Byte

后端 未结 5 1870
北海茫月
北海茫月 2021-02-14 15:31

I have some data in field type Byte ( I save eight inputs in Byte, every bit is one input ). How to change just one input in that field ( Byte) but not to lose information about

5条回答
  •  半阙折子戏
    2021-02-14 16:23

    To set the seventh bit to 1:

    b = (byte) (b | (1 << 6));
    

    To set the sixth bit to zero:

    b = (byte) (b & ~(1 << 5));
    

    (The bit positions are effectively 0-based, so that's why the "seventh bit" maps to 1 << 6 instead of 1 << 7.)

提交回复
热议问题