Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Type Cast

 
kantu Deshpande
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!!,
byte b;
int i=257;
b= (byte)i;
If I type cast as shown above, I'm getting answer b=1. But, if I intialize int i=144 I'm getting the answer b=-112. Can any body explain how this type casting been done. Please if you give me one example, I would really appreciate.
Thanks,
Kantu

 
Alagu Seenivasan
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by kantu Deshpande:
Hi!!,
byte b;
int i=257;
[b]b= (byte)i;

If I type cast as shown above, I'm getting answer b=1. But, if I intialize int i=144 I'm getting the answer b=-112. Can any body explain how this type casting been done. Please if you give me one example, I would really appreciate.
Thanks,
Kantu
[/B]

int i=257 is represented as 0000 0001 0000 0001
when you cast an int into byte only the lower order bits are copied
so byte b= 0000 00001 which is 1.

int i=144 is represented as 0000 0000 1001 0000
1001 0000 (in 2's complement form) represents -112.
-------------------
(to get the 2's complement of 112)
112 = 0111 0000
1' complement = 1000 1111
add 1 = 1001 0000

[ for more info search this forum for the words - 2's complement ]

[This message has been edited by Alagu Seenivasan (edited October 05, 2000).]
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ...
Another way to find the 2's complement is to subtract the number from the highest allowable value and set it negative

Hope that helps.
------------------
Jane
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One thing that helped me with this is to remember that the minimum and maximum value for a byte is -128 and 127 (2 to the 7th and 2 to the 7th - 1). Both of the numbers you provided are out of this range, and that is when you start to get the funny answers. That is why Java makes you explicitly cast when you are casting down, because you might get a different answer than you expected because you are losing bits of information.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic