Donald Gooden wrote:Hello all I am using Ivor Hortons beginning java 7th addition and I am having a hec of a time understanding the the bit wise operators, casting, op operators use,shift operators, just the whole math section of chapter two past the basic math operators.
I'm not sure how your book tackles it, but when I've tried to explain it, I've always found it best to start with a single bit (0/1) and the basic operations ('&', '|', '^' and '~') first, before you move on to whole words and bit shifting.
First: it's worth remembering the name of the operator:
& = 'AND'
| = 'OR'
^ = 'Exclusive OR'
~ = 'NOT'
Second: For a single bit:
0 = false
1 = true
So, given that, when you are given something like '1 & 0', just write it out in longhand:
true AND false
What would you expect the result of that to be? Now convert it back to a single bit value (1 or 0).
And '~1' ('~' only takes a single argument) becomes:
What would you expect the result of that to be?
'^' is the trickiest one because it's not something we normally find in speech, but the easiest way I find to remember it is to rename it:
'^' = 'Is different to'
and use the same technique as above.
So: what will the result of '1 ^ 1' be? Again, write it out in longhand...
After that, it's simply learning how they operate on groups of bits (which is all an int, or a byte really are):
I suspect also that what you really want to know is why they exist, and a lot of it is historical. They were the first real instructions computers had, because they were the result of applying current (or voltage) across a single transistor. And even now, in the days of chips, they are blisteringly fast - often only a single cycle of your CPU; which these days are measured in gigahertz.
And you can do some amazing things with them. Just one quick example:
'^' means "is different to"; therefore, x ^ x must equal 0 (false). So, if you have a pile of memory that you need to set to 0 - a very common requirement - just divide it into bytes (or ints, or longs) and '^' each one with itself.
And that's exactly how computers used to do this (not sure about now), because it was by far the quickest way.
These days, they're more of a curio than anything, and it's unlikely that you'll need to use them a lot when you program; but for certain low-level operations, they're still the fastest way to go.
As for shifting: My advice - get your head around those four operators above first, and make sure you really understand them; then tackle shifting. One thing at a time.
Hope it helps.