Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# operators

sona gold
Ranch Hand
Posts: 234
could anyone please explain bitwise operator, the right shift and left shift. i am new to java
and can't make anything out of these

Manfred Leonhardt
Ranch Hand
Posts: 1492
Hi,
To make use of bitwise operators you must think in binary. In Java there are 3 types of shift operators:
1. << (Shift Left) - Shift all bits left n times, filling with zeros.
2. >> (Shift Right) - Shift all bits right n times, filling with the sign bit.
3. >>> (Shift Unsigned Right) - Shift all bits right n times, filling with zeros.
Lets take some examples:
Start: 0000 0000 0000 0000 0000 0000 0000 1100
Shift Left#1: 0000 0000 0000 0000 0000 0000 0001 1000
Shift Left#2: 0000 0000 0000 0000 0000 0000 0011 0000
Shift Left#3: 0000 0000 0000 0000 0000 0000 0110 0000
Shift Left#4: 0000 0000 0000 0000 0000 0000 1100 0000
Convert Bin to Dec: 1*128 + 1*64 = 192
Start: 42 --> 0000 0000 0000 0000 0000 0000 0010 1010
1's Comp: 1111 1111 1111 1111 1111 1111 1101 0101
2's Comp: 1111 1111 1111 1111 1111 1111 1101 0110
-42: 1111 1111 1111 1111 1111 1111 1101 0110
Shift Right#1: 1111 1111 1111 1111 1111 1111 0110 1011
Shift Right#2: 1111 1111 1111 1111 1111 1111 1011 0101
Shift Right#3: 1111 1111 1111 1111 1111 1111 1101 1010
Shift Right#4: 1111 1111 1111 1111 1111 1111 1110 1101
1's Comp: 0000 0000 0000 0000 0000 0000 0000 0010
2's Comp: 0000 0000 0000 0000 0000 0000 0000 0011
Start: 1111 1111 1111 1111 1111 1111 1101 0110
Shift Right#1: 0111 1111 1111 1111 1111 1111 1110 1011
Shift Right#2: 0011 1111 1111 1111 1111 1111 1111 0101
Shift Right#3: 0001 1111 1111 1111 1111 1111 1111 1010
Shift Right#4: 0000 1111 1111 1111 1111 1111 1111 1101
Answer: 268435453 (take my word on this ...)
Regards,
Manfred.

Roseanne Zhang
Ranch Hand
Posts: 1953
You can certainly play and learn:
BitShift
and
Cat and Mouse Games with Bits
You will learn a lot about bits and binary stuff, when you're playing and having fun.
Roseanne

Elisabeth Van
Ranch Hand
Posts: 42
As a "newbie" programmer, I'd like to know an example of when/why you would use bitwise operators. Haven't encountered a need for it yet, but I'm sure there are reasons one would work with that.
Thanks!

sona gold
Ranch Hand
Posts: 234
thanks everyone
well i myself don't know where i would use bitwise operator elizabeth
but the thing is it is on the list of sjcp exams
and hence the need

sona gold
Ranch Hand
Posts: 234
thanks
but if i understand clearly everytime i have to convert the given number into binary and then find the result accordingly
right