Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# Doubts on shift operations

Kiran Chand Panga
Ranch Hand
Posts: 31
class TEST1
{
public static void main(String[] args) {
byte x=3, y=5;
System.out.println((-x == ~x+1) + ","+(-y == ~y+1));
}
}

class TEST2
{
public static void main(String[] args) {
byte x=127;
x<<=2;
System.out.println(x);
}
}

class TEST3
{
public static void main(String[] args) {
byte y=5;
System.out.println(y<<33);
}
}

Can any one help out in solving the shift operations(<<,>>,<<< ?

Keith Lynn
Ranch Hand
Posts: 2409
What question do you have?

Kiran Chand Panga
Ranch Hand
Posts: 31
Can you tell me how to solve these three Problems (which I posted earlier)?
[ March 01, 2006: Message edited by: Kiran Chand Panga ]

Keith Lynn
Ranch Hand
Posts: 2409
Originally posted by Kiran Chand Panga:
class TEST1
{
public static void main(String[] args) {
byte x=3, y=5;
System.out.println((-x == ~x+1) + ","+(-y == ~y+1));
}
}

This is simply testing that in order to form the negative of a number you flip the bits and add 1.

class TEST2
{
public static void main(String[] args) {
byte x=127;
x<<=2;
System.out.println(x);
}
}

Basically this is shifting 2 0s onto the end of the bits 01111111. When you do this you get 11111100. This is -4.

class TEST3
{
public static void main(String[] args) {
byte y=5;
System.out.println(y<<33);
}
}

Before the shift operation is carried out, we mod 33 by 32. So we are shifting 1 bit.

So we get 10.

mohit junejaa
Ranch Hand
Posts: 41
CONDITIONS:

ONLY VALID FOR NON NEGATIVE NOS

in most cases it will work except for cases in which final result using this becomes greater than pow(2,31)-1:

1) in case of << :
suppose expression is a<<b

2) in case of >> or >>>
final expression::
a/pow(2,b)

BUT DO REMEMBER THE ABOVE CONDITIONS . IF "a" DOES NOT SATISFY THE CONDITIONS DONT USE THIS TECHNIQUE

Bert Bates
author
Sheriff
Posts: 8898
5
Remember sports fans - shift operators are on the 1.4 exam, but they are NOT on the 1.5 exam!