解决方案 »

  1.   

    探讨下吧:
    个人感觉转换为int型的含义是,先将待计算的参数转换为int,然后再进行计算。
      

  2.   

    先转int再做位移操作
    所以你的第二点是对的
    这应该没什么歧义吧?至于你的第一个观点,你没理解java的解释吧,是先转再移而不是先移再转
      

  3.   


    谢谢,但是我在网上有看到说byte、char等移位只针对低5位,long是针对低6位,否则会影响最终结果int的值,是这样吗?感觉好像都是从最高位开始移吧
      

  4.   

    “在网上有看到说byte、char等移位只针对低5位,long是针对低6位,真是这样吗?没法理解,好像也和测试不符。”
    上面说法是对的。参考《The Java™ Language
    Specification
    Java SE 7 Edition》15.19 Shift OperatorsIf the promoted type of the left-hand operand is int, only the five lowest-order bits
    of the right-hand operand are used as the shift distance. It is as if the right-hand
    operand were subjected to a bitwise logical AND operator & (§15.22.1) with the
    mask value 0x1f (0b11111). The shift distance actually used is therefore always in
    the range 0 to 31, inclusive.
    If the promoted type of the left-hand operand is longthen only the six lowestorder
    bits
     of the right-hand operand are used as the shift distance. It is as if the
    right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1)
    with the mask value 0x3f (0b111111). The shift distance actually used is therefore
    always in the range 0 to 63, inclusive.
      

  5.   


    嗯,原来是我没有仔细看清,上面说的低5位,低6位是针对右操作数,即你要移动多少位来说的,并不是针对做操作数而言的。大家可以参考下这篇文章,觉得讲得蛮清楚的:http://www.360doc.com/content/07/1112/14/15458_818168.shtml. 其实问这么多就是想自己能够写出int转2进制,16进制的算法,发现还不是很理解。这个是jdk中int转2进制的算法,谁可以帮忙解释下算法:public static String toBinaryString(int i) 
    {
    return toUnsignedString(i, 1);
    } /**
      * Convert the integer to an unsigned number.
     */
     private static String toUnsignedString(int i, int shift) 
    {
    char[] buf = new char[32];
    int charPos = 32;
    int radix = 1 << shift;
    int mask = radix - 1;
    do 
           {
        buf[--charPos] = digits[i & mask];
        i >>>= shift;
    } while (i != 0); return new String(buf, charPos, (32 - charPos));
     }
      

  6.   

    我没法给你答案,只说一点,在byte,shor,char 参与运算的时候,会先自动转为int类型,再运算,这是java虚拟机设计成这样的