有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有人能解释一下这种移位/长时间修补输出吗?

运行1:

public static void main(String[] args) {

        System.out.println("shiftwise Example A = " + (0x47494638 << 32));

        long someNumber = 0x47494638;
        long otherNumber = someNumber << 32;

        System.out.println("shiftwise Example B = " + otherNumber);



    }

输出:
shiftwise示例A=1195984440
shiftwise示例B=5136714056324874240

运行2:(我刚刚在示例A中指定了“L”):

public static void main(String[] args) {

        System.out.println("shiftwise Example A = " + (0x47494638L << 32));

        long someNumber = 0x47494638;
        long otherNumber = someNumber << 32;

        System.out.println("shiftwise Example B = " + otherNumber);



    }

输出:
shiftwise示例A=5136714056324874240
shiftwise示例B=5136714056324874240


共 (2) 个答案

  1. # 1 楼答案

    该值被视为int,可以这样模拟:

    运行3:

    public static void main(String[] args) {
        System.out.println("shiftwise Example A = " + (0x47494638 << 32));
    
        int someNumber = 0x47494638;
        long otherNumber = someNumber << 32;
    
        System.out.println("shiftwise Example B = " + otherNumber);
    }
    

    输出:

    shiftwise Example A = 1195984440
    shiftwise Example B = 1195984440

  2. # 2 楼答案

    如果未指定L后缀,则常量文字值将被视为int,并且§15.19 of the Java Language Specification中的此文本适用于:

    If the promoted type of the left-hand operand is int, then 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.

    因此,您的左移位32位被转换为位的移位,即没有变化