Results 1 to 4 of 4

Thread: Double to Byte

  1. #1
    Javasubbu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

    Default Double to Byte

    Hi,

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

    Java 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?

  2. #2
    christopherx is offline Member
    Join Date
    Oct 2011
    Posts
    92
    Rep Power
    0

    Default 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 :)

  3. #3
    diamonddragon is offline Senior Member
    Join Date
    Jan 2012
    Posts
    210
    Rep Power
    3

    Default Re: Double to Byte

    Quote Originally Posted by christopherx View Post
    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...

  4. #4
    Javasubbu is offline Member
    Join Date
    Oct 2011
    Posts
    19
    Rep Power
    0

Similar Threads

  1. byte[] to double[][]
    By kkGG in forum Advanced Java
    Replies: 16
    Last Post: 01-23-2012, 04:54 AM
  2. Replies: 1
    Last Post: 10-21-2011, 12:55 PM
  3. Read a bitmap byte by byte
    By cbr400aero in forum Java 2D
    Replies: 2
    Last Post: 10-19-2010, 12:42 AM
  4. Replies: 1
    Last Post: 04-21-2010, 03:28 AM
  5. Double.valueOf() vs Double.parseDouble()
    By greenbean in forum New To Java
    Replies: 10
    Last Post: 01-12-2009, 09:39 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •