• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to use Bitwiae operators?

 
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


The above is from the book I am reading these days.It says"gives you a one if the forth bit from the right in the binary representation of n is 1 and 0 if not".

Can you explain this a bit further.
Are the operators &, |, ^, ~ bitwise operators?
I thought >>>, >> are the bitwise operators.
Where can I get some more information about bitwise operators?
Why do we have bitwise operators, during what situations are they used?

Varuna
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
&, |, ^, and ~ are bitwise operators.

>>>, >>, and << are bit shift operators.

See Java Tutorial - Bitwise and Bit Shift Operators.

With respect to your example, the & operator compares two values bit by bit (bitwise), and returns a 1 if both values have a 1 in that position. In other words, if the first value has a 1 in that position AND the second value also has a 1 in that position. Otherwise, it returns a 0.

For example, suppose you have two binary values: 1100 and 1010. Applying the & operator to these values would result in 1000, because the fourth bit from the right is the only position in which both values have a 1.

So consider (n&8)/8. In binary, 8 is 00001000. So if you have some other value 'n', then n&8 will result in 00000000 if the fourth bit of n is zero, or 00001000 if the fourth bit of n is one. Dividing this by 8 results in either 0 or 1 respectively -- which tells you what the fourth bit of n is.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Instead of 8 try 1 << 3, so you end up with

(i & (1 << 3)) >> 3
reply
    Bookmark Topic Watch Topic
  • New Topic