English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I'm teaching a class on type conversions in Java, and I've run into something that I don't know myself. Here is a simple bit of code to show how type conversions are sometimes unreliable.

long l = 1000;
byte b = (byte) l;
System.out.println(b); // -24 (Unsure how Java arrives at this value)
System.out.println(l); // 1000

The variable "long l" is set to 1000. It is then converted to "byte b". "byte" can only hold values from -128 to 127. When I print variable "b", it prints a gibberish number of "-24".

How does Java arrive at "-24" when converting "1000" to fit into a "byte"? Is this value predictable?

2007-07-05 04:10:20 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

4 answers

Whilst the values listed for the byte are -128 to 127 the storage will actually hold a value of 255. The values you actually see are because the right most bit is the sign bit and 2's complement is used.
So take the binary value of 1000
1111101000
now truncate it
11101000
Now take the 2's complement
10011000
and you now have -24.
I have no idea why your virtual machine is doing this though and I cannot tell if all vm's will work this way.

I hope this helps.

2007-07-05 04:27:21 · answer #1 · answered by AnalProgrammer 7 · 0 0

The bit representation of 1000 is

1111101000, however casting to a byte truncates the number to the 8 right-most bits --> 11101000

signed bytes in Java are stored as two's complement values. The first bit signifies that the number is negative. The absolute value of the number is calculated by inverting the 7 remaining bits, and in the case of a negative number subtracting an additional 1.

inversion of the 7 bits gives 0010111 which is decimal 23, since the number of negative we substract an additional 1, so -24.

Completely predicatable.

2007-07-05 04:32:34 · answer #2 · answered by Anonymous · 1 0

Check this website. It appears that the numbers are truncated and are not predicatable. I would think this would be the case anytime your taking a large value and trying to put it into a small value. Even in Java with its ability of inheritance this would cause problems.

http://mindprod.com/jgloss/conversion.html#TRUNCATION

2007-07-05 04:17:47 · answer #3 · answered by Anonymous · 1 0

checklist me in case you like for being a *****, I formally do no longer care yet Nateena is a bloody liar. 4% of her solutions are ultimate solutions. never been given a ultimate answer? Take a protracted walk off a short cliff you mendacity rat. yet that grow to be a particularly stable humorous tale. did no longer make me snigger besides the undeniable fact that it grow to be unique.

2016-11-08 05:25:11 · answer #4 · answered by ? 4 · 0 0

fedest.com, questions and answers