a quizz question about java bit operation???

T

tyshanchn

hi ,


what is the value of

-8>>-1
-8<<-1


it will be like

public class BitOperation {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(-8 << -1);
System.out.println(-8 >> -1);
}

}

the result is
0
-1


but if not -8, what will be the value?and why???
 
J

James McGill

hi ,


what is the value of


without considering java, -8 in 2's complement is (pretending it's a 16
bit value for the moment)

1111 1111 1111 1000

and -1 is

1111 1111 1111 1111


Then when you take these signed values and feed them to an unsigned
operation like shift,

You're asking to shift right by the maximum number that can be
represented in you bit width, and I would expect that to be a
sign-extended negative number, and if you evaluate it as a signed
result, I'd expect to see -1.

Likewise

You're asking to shift left by way more bits than exist in the value, so
you end up with all zeros, and I'd expect the answer to be zero.
System.out.println(-8 << -1);
System.out.println(-8 >> -1);
the result is
0
-1

Yep.

I don't understand your last question. "If not -8..."

There is a well defined behavior for this sort of operation and I don't
see anything strange or unexpected from your example.
 
M

Matt Atterbury

tyshanchn said:
what is the value of

-8>>-1
-8<<-1


it will be like

public class BitOperation {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(-8 << -1);
System.out.println(-8 >> -1);
}

}

the result is
0
-1


but if not -8, what will be the value?and why???

Presumably "<< -1" means "left shift many times" and not "right shift
by 1", due to -1 being converted to an unsigned value (with all bits
set).

So, a negative number right shifted enough times must become -1,
and a negative number left shifted enough times must become 0.

m.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top