Change bits value in Byte

后端 未结 5 1743
北海茫月
北海茫月 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;
    }
    

提交回复
热议问题