Change bits value in Byte

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

    To set a bit use :

    public final static byte setBit(byte _byte,int bitPosition,boolean bitValue)
    {
        if (bitValue)
            return (byte) (_byte | (1 << bitPosition));
        return (byte) (_byte & ~(1 << bitPosition));
    }
    

    To get a bit value use :

    public final static Boolean getBit(byte _byte, int bitPosition)
    {
        return (_byte & (1 << bitPosition)) != 0;
    }
    
    0 讨论(0)
  • 2021-02-14 16:06

    Note that the "Byte" wrapper class is immutable, and you will need to work with "byte".

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-14 16:22

    You really owe it to yourself to look into masking functions for and, or, and xor -- they allow you to simultaneously verify, validate, or change... one, some, or all of the bits in a byte structure in a single statement.

    I'm not a java programmer by trade, but it's derived from C and a quick search online seemed to reveal support for those bitwise operations.

    See this Wikipedia article for more information about this technique.

    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题