不理解将double类型转换为byte类型的结果

3

你好,我从我的书中得到了一个任务,需要编写以下代码:

public class EkspKonverzija 
{
    public static void main(String args[])
    {
        byte b;
        int i=257;
        double d= 323.142;

        b=(byte) i;
        System.out.println("i and b "+i+" "+b);

        i=(int) d;
        System.out.println("d and i "+d+" "+i);

        b=(byte) d;
        System.out.println("b and d "+b+" "+d);


    }
}

结果是:

i 和 b 257 1

d 和 i 323.142 323

d 和 b 323.142 67

我理解为什么第一个转换的结果是1,也理解第二个转换,但我不理解为什么最后一个转换的结果是67,我无法想通,所以需要您的帮助。谢谢。


3
323 - 256 = 67。就是这样。 - nhahtdh
我现在明白了。谢谢。 - user3266796
1
http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3 - Sotirios Delimanolis
1个回答

5
所有这些都被称为缩小原始类型转换(§5.1.3)
  1. The conversation to (byte):

           257 = 0000 0001 0000 0001
    

    Truncating the high byte gives:

    (byte) 257 = xxxx xxxx 0000 0001
    

    which is obviously 1.

  2. The conversation from a floating point to an integer is always round to zero.

  3. The conversation from double to byte happens in two steps:

    1. The double gets casted to an int, following the round to zero rule.

      (int) 323.142  ~~~>  323
      
    2. The int gets truncated to a byte.

      (byte) 323     ~~~~> 67
      
             323 = 0000 0001 0100 0011
      (byte) 323 = xxxx xxxx 0100 0011
                 = 67
      

现在明白了,非常感谢。这对我很有帮助,谢谢! - user3266796
@miljannet:您可以接受此答案作为帮助您解决问题的答案。请点击我的分数下面的复选标记来执行此操作。 - Martijn Courteaux
1
我还是这个网站的新手,我需要至少15个积分才行。 - user3266796
哦,好的。我真的记不住那个。现在你可以 :) - Martijn Courteaux
实际上看起来你没有或者可能撤销了它。因为它没有被接受。 - Martijn Courteaux
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接