Help debug -Type conversion program in java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • poojagupta1984
    New Member
    • Mar 2008
    • 1

    Help debug -Type conversion program in java

    What i know is:
    In java, all byte and short data types are automatically promoted to int during a calculation. And, if you are casting a large data type like int to a byte then the int is reduced modulo the range of the short data type i.e byte (the range of byte is 256).

    The program below has no compilation error. The output is incorrect for the first print statement..plea se explain why?

    [CODE=Java]class TestByte
    {
    public static void main(String args[])
    {
    byte b = 50, c=50;
    int i;
    i=b*60;
    b=(byte)(b*60);
    c=(byte)(c*6);
    System.out.prin tln(b); // should be 184
    System.out.prin tln(c); // should be 44
    System.out.prin tln(3000%256); //should be 184
    System.out.prin tln(i); // should be 3000
    }
    }[/CODE]


    Output:
    -72
    44
    184
    3000
    Last edited by BigDaddyLH; Mar 5 '08, 05:24 PM. Reason: added code tags
  • BigDaddyLH
    Recognized Expert Top Contributor
    • Dec 2007
    • 1216

    #2
    Please enclose your posted code in [code] tags (See How to Ask a Question).

    This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

    Please use [code] tags in future.

    MODERATOR

    Comment

    • BigDaddyLH
      Recognized Expert Top Contributor
      • Dec 2007
      • 1216

      #3
      Why -72 instead of 184? Like long, int and short, type byte is signed. Its range of values is

      -128 <= x <= 127

      If you look at the bit pattern for 184:

      10111000

      The high bit is on. This means it's the 2's complement representation of a negative number, the negation of 256-184 or 72. Thus the result is -72.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        If the OP insists to see the value 184 use the bitmask operator & as in b&0xff
        where b is the byte. Both operands are converted to ints and the bitwise and
        operator chops off everything except the lowest eight bits which can represent
        values in the range [0,255]

        kind regards,

        Jos

        Comment

        Working...