开发者

Change bits value in Byte

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 others ( example change seventh bit to one, or change sixth bit to zero )?


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.)


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.


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;
}


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜