Double to Byte

• 02-03-2012, 08:36 PM
Javasubbu
Double to Byte
Hi,

I am learning Java and I do not understand the output for Double to Byte conversion.

Code:

```class Conversion { public static void main(String args[]) { byte b; int i = 257; double d = 323.142; System.out.println("\nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("\nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("\nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); } }```
The output is
Conversion of double to byte.
d and b 323.142 67

Why is output 67? any thoughts?
• 02-03-2012, 08:45 PM
christopherx
Re: Double to Byte
A byte can only hold from -127 - 127.

This is because it is 8 bits long. (otherwise known as a Byte!)

In an 8 bit binary number stored in two's compliment notation, the biggest value that can be represented is 127.

The reason you've ended up with 67 is that the Java runtime environment has lost a ton of bits trying to store 323 :)
• 02-03-2012, 10:04 PM
diamonddragon
Re: Double to Byte
Quote:

Originally Posted by christopherx
The reason you've ended up with 67 is that the Java runtime environment has lost a ton of bits trying to store 323 :)

And no exception at sight...
• 02-05-2012, 10:03 AM
Javasubbu
Re: Double to Byte