Link to home
Start Free TrialLog in
Avatar of kishoretnn
kishoretnn

asked on

How to set and read individual bits from a byte using java

I have a requirement to define a variable as byte in java. And I need to set and access individual bits from the byte to do specific operations like (example) if first bit is 1 then some action and so on.
ASKER CERTIFIED SOLUTION
Avatar of sciuriware
sciuriware

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RishadanPort
RishadanPort

You can use the the following bitwise operators (some examples given from the experts above):

Bitwise And Operation:
k = 2 & 1;    // result 0    
k = 2 & 2;   //result 2
k = 3 & 1; //result 1

Example of k=3&1    (Basically you compare each bit and if both bit places are same keep them)
  00000011
&00000001
  ------------
  00000001


Bitwise Or Operation:
k = 2 | 1;    // result 3    
k = 2 | 2;   //result 2
k = 3 | 1; //result 3

Example:

Example of k=3&1    (Keep all bits with 1s)

  00000011
| 00000001
  ------------
  00000011


Bitwise Shift operators >>, << 

k = 1 << 1  // result k = 2
k = 1 << 2  //result k = 4
k = 4 >> 1 //result k = 2
k = 4 >> 2 // result k = 1

Here the << operator shifts all bits to the Right (increasing), and the >> operator shifts all bits to the left (decreasing)
 
One more note:

the bitwise shift operators:

>>>, and <<< are exactly the same as the >>, << operators, expect that they have the extra >, <
To RishadanPort: Not exactly!
First of all <<< does not exist. Second, >> is right shift with sign extension and >>> is right shift with zero extension.

http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5121
interesting. I think I was thinking of C++ or C
The BitSet that CEHJ mentioned is a universal solution.
the operators | & << >> and >>> are much faster when applied
on an int, but restricted  to 32 bits.

;JOOP!