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.
kishoretnnAsked:
Who is Participating?
 
sciuriwareConnect With a Mentor Commented:
1) use int.

2) set:    int k;   k |= 1;
   or         k |= 1<<5;   //  (00100000)

3) read:   int m =  k & (1<<3);

although, boolean result is better:

boolean h = (k & (1<<3)) != 0;  // 1 == true.

;JOOP!
0
 
CEHJConnect With a Mentor Commented:
You could always turn it into a BitSet then it could be a bit easier for you
0
 
RishadanPortCommented:
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)
 
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
RishadanPortCommented:
One more note:

the bitwise shift operators:

>>>, and <<< are exactly the same as the >>, << operators, expect that they have the extra >, <
0
 
CokoVokoCommented:
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
0
 
RishadanPortCommented:
interesting. I think I was thinking of C++ or C
0
 
sciuriwareCommented:
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!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.