permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes pls explain? 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 "pls explain?" Watch "pls explain?" New topic
Author

pls explain?

vikram choudhary .
Greenhorn

Joined: Apr 25, 2007
Posts: 7
byte i= (byte)129;
System.out.println(i);

output: -127 why?
can anyone explain?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
As an int, 129 has the following bit representation

00000000000000000000000010000001

When you cast to a byte, you only have the last 8 bits.

So you have the byte

10000001

Because the first bit is a 1, this is a negative number.

To find out what number it is the negative of, flip all the bits and add 1

You get

01111111

So the number is -127.
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Good Keith!!!



Thanks,
cmbhatt


cmbhatt
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: pls explain?
 
Similar Threads
byte range
Casting int to byte (was: pls explain)
byte range
simple Bitwise
isn't this strange?