gpt4 book ai didi

java - 切换文字位大小

转载 作者:行者123 更新时间:2023-12-03 03:26:31 26 4
gpt4 key购买 nike

我正在玩换档,但我遇到了一个问题:

    int maxint = Integer.MAX_VALUE;
LOG.debug("maxint << 31 ---> {} ({})", maxint << 31 , Integer.toBinaryString(maxint << 31 ));
LOG.debug("maxint << 32 ---> {} ({})", maxint << 32 , Integer.toBinaryString(maxint << 32 ));
LOG.debug("maxint << 33 ---> {} ({})", maxint << 33 , Integer.toBinaryString(maxint << 33 ));

它打印:

maxint <<  31  --->  -2147483648 (10000000000000000000000000000000)
maxint << 32 ---> 2147483647 (1111111111111111111111111111111)
maxint << 33 ---> -2 (11111111111111111111111111111110)

所以问题是,如果shift 31在MSB留下'1',那么shift 32不应该将其移出并返回0?

更进一步,我从移位 31 结果(即 Integer.MIN_VALUE)开始执行相同的操作,然后移位 1。

    int minInt = -2147483648;
LOG.debug("minInt << 1 ---> {} ({})", minInt << 1 , Integer.toBinaryString(minInt << 1 ));
LOG.debug("minInt << 2 ---> {} ({})", minInt << 2 , Integer.toBinaryString(minInt << 2 ));

它打印:

minInt  <<  1 --->  0 (0)
minInt << 2 ---> 0 (0)

这正是我所期望的。

最佳答案

http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19

If 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.

类似地,六位表示长整型。这种行为在 C 和 C++ 中也是允许的,并且通常实现,但不像 Java 中那样要求。

也是 Shift operator in Java bizarre program output 的重复项我的第一次搜索错过了。

关于java - 切换文字位大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com