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 negative representation 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 "negative representation" Watch "negative representation" New topic
Author

negative representation

Harvinder Singh
Ranch Hand

Joined: Feb 14, 2003
Posts: 90
//1byte b= 0000 0000//ouput is Zero
//2byte b1=1000 0000//compiler error casting is required
//3byte b3=byte(1000 0000)//-128
question: 0 and -128 are both in the range then why the casting is required.
if u have few extra minutes then do tell me how we represent -ve numbers in binary.2's complement is ok but I make a lot of mistakes when I try to do that manually.particularly in substracting binary numbers.thanks


Hard work beats talent<br />when talent doesn't work hard.<p> - Tim Notke
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
If you use a literal value, such as 10000000, the compiler automatically interprets that as an int. Therefore, 10000000 isn't the binary version of -128, it's 10,000,000, which certainly doesn't fit into a byte. Check out the JLS, §3.10.1 Integer Literals for more information.
As far as representation of values in 2's complement, here's the easiest way I know to perform the conversion:
Let's say you want to get the binary equivalent to -73. First, get the binary value of it's absolute value, 73. The binary equivalent of 73 is:
01001001
Now, flip the bits:
10110110
Finally, add 1:
10110110 + 1 = 10110111
So, the binary representation of -73 is 10110111.
I hope that helps,
Corey


SCJP Tipline, etc.
Shafkat Talli
Ranch Hand

Joined: Aug 01, 2003
Posts: 30
If this is -128, what is 127 then ? i thought this was 127 ??? now i dont get it anymore.
1000 0000)//-128


---------------------------<br />Shafkat Talli<br />SCJP 1.4, August 2003.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Shafkat Talli:
If this is -128, what is 127 then ? i thought this was 127 ??? now i dont get it anymore.
1000 0000)//-128

The binary equivalent of 127 is 01111111.
The leftmost bit is a "sign bit." If it's a 0, the number is positive, if it's 1, the number is negative.
Check out this campfire story. You'll find a lot of good information there. Also, if you're confused, do some searches in this forum.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: negative representation
 
Similar Threads
How this output is coming regarding left shift operator
Expressions
Mock Exam Question
byte shift
cast to bytes