Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2006

Tip: Looking for answers? Try searching our database.

a quizz question about java bit operation???

Thread view: 
tyshanchn - 10 May 2006 04:03 GMT
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???
James McGill - 10 May 2006 04:30 GMT
> 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,

> -8>>-1

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

> -8<<-1

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.
Matt Atterbury - 10 May 2006 05:03 GMT
> what is the value of
>
[quoted text clipped - 21 lines]
>
> 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.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.