posted 17 years ago

How do shift operators work when the right operand is negative? for instance, how is the value calculated for

int result = 12 << -3;

int result = 12 << -3;

Sharon

posted 17 years ago

What I do is

12 << -3 <br /> take the last 5 bits (when LHS is int) --> 1 1101<br /> treat this as a normal +ve number<br /> 0001 1101 ---> 0x1D -- > 29

Now 12 is --> 0000 .....0000 1100

So its 000 ....0000 1100 << 29<br /> If you do this you'll find the most significant bit gets the 1<br /> --> 1000 ....0000 ... ---> -2147483648 or Integer.MIN_VALUE

This is the way I do and the answers come out right .I dont know whether its the correct method or not.

Can any one confirm if I am doing the right thing here..

Mousami

12 << -3 <br /> take the last 5 bits (when LHS is int) --> 1 1101<br /> treat this as a normal +ve number<br /> 0001 1101 ---> 0x1D -- > 29

Now 12 is --> 0000 .....0000 1100

So its 000 ....0000 1100 << 29<br /> If you do this you'll find the most significant bit gets the 1<br /> --> 1000 ....0000 ... ---> -2147483648 or Integer.MIN_VALUE

This is the way I do and the answers come out right .I dont know whether its the correct method or not.

Can any one confirm if I am doing the right thing here..

Mousami

Sharada Kumaran

Greenhorn

Posts: 29

posted 17 years ago

Wow, Mousami. That logic does work. but how did you get such a method? And what is the reasoning behind it. How does it work?

Anyway, I will use yr method. feel more confident about handling bit shifts. Do you know if there are questions in the certification on shift operations on floats/doubles? Does it make sense, 'coz i haven't seen such questions.

Thanks for the interesting solution.

Anyway, I will use yr method. feel more confident about handling bit shifts. Do you know if there are questions in the certification on shift operations on floats/doubles? Does it make sense, 'coz i haven't seen such questions.

Thanks for the interesting solution.

Sharon

Consider Paul's rocket mass heater. |