Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change bits value in Byte

Tags:

java

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

like image 387
Damir Avatar asked Jan 30 '11 17:01

Damir


2 Answers

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

like image 77
dkarp Avatar answered Nov 04 '22 04:11

dkarp


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.

like image 14
starblue Avatar answered Nov 04 '22 02:11

starblue