Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Head First Android this week in the Android forum!

# Doubts on shift operations

Kiran Chand Panga
Ranch Hand

Joined: Feb 02, 2006
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(<<,>>,<<< ?

Thanks & Regards <br /> <br />Kiran Chand Panga<br />SCJP1.4
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
What question do you have?
Kiran Chand Panga
Ranch Hand

Joined: Feb 02, 2006
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Feb 24, 2006
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

scjp 1.4
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8898

5
Remember sports fans - shift operators are on the 1.4 exam, but they are NOT on the 1.5 exam!

Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)

I agree. Here's the link: http://aspose.com/file-tools

subject: Doubts on shift operations