Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# negative representation

Harvinder Singh
Ranch Hand
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

Corey McGlone
Ranch Hand
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
10110110 + 1 = 10110111
So, the binary representation of -73 is 10110111.
I hope that helps,
Corey

Shafkat Talli
Ranch Hand
Posts: 30
If this is -128, what is 127 then ? i thought this was 127 ??? now i dont get it anymore.
1000 0000)//-128

Corey McGlone
Ranch Hand
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.