This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes S.o.p (byte) 0X81 >> 2 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "S.o.p (byte) 0X81 >> 2" Watch "S.o.p (byte) 0X81 >> 2" New topic
Author

S.o.p (byte) 0X81 >> 2

Rosie Nelson
Ranch Hand

Joined: Nov 06, 2001
Posts: 31
What is the result of the following fragment of code?
(byte) 0X81 >> 2

I am confused about the output of the following code. I undersatand that (byte)0X81 is promoted to an int - unary promotion. I would expect the following output:-

0000 0000 0000 0000 0000 0000 1000 0001 >> 2 gives rise to:-
0000 0000 0000 0000 0000 0000 0010 0000 = 0x20
but this is incorrect. Can somebody please explain where I'm going wrong?
Jennifer Warren
Ranch Hand

Joined: Aug 24, 2001
Posts: 53
try doing this (byte)(0x81 >>2);
check out the result.
Jennifer.
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
0000 0000 0000 0000 0000 0000 1000 0001

cast to a byte gives
1000 0001

Notice the 1 in the left-most position. Therefore it is a negative number (actually decimal -127).

Expand to an int
1111 1111 1111 1111 1111 1111 1000 0001

Shift right 2
1111 1111 1111 1111 1111 1111 1110 0000

It is still a negative number (decimal -32)

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Rosie Nelson
Ranch Hand

Joined: Nov 06, 2001
Posts: 31
Thank you Marilyn.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: S.o.p (byte) 0X81 >> 2
 
Similar Threads
How this output is coming regarding left shift operator
>> shift question
Shift Operator
bit shift
byte to integer conversion -- mock exam qtn