Change bits value in Byte

后端 未结 5 1756
北海茫月
北海茫月 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:22

    Declare b as the primitive type byte:

    byte b = ...;
    

    Then you can use the compound assignment operators that combine binary operations and assignment (this doesn't work on Byte):

    b |= (1 << bitIndex); // set a bit to 1
    b &= ~(1 << bitIndex); // set a bit to 0
    

    Without the assignment operator you would need a cast, because the result of the | and & operations is an int:

    b = (byte) (b | (1 << bitIndex));
    b = (byte) (b & ~(1 << bitIndex));
    

    The cast is implicit in the compound assignment operators, see the Java Language Specification.

提交回复
热议问题