移位运算符:用于 char、byte、short 和 long 的低位位数。
Shift Operator: Number of low-order bits being used for char, byte, short and long.
在思考 Java 时,有一个会话介绍了 Shift Operators,内容如下:
"If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you're operating on a long, you'll get a long result. Only the six low-order bits of the right-hand side will be used, so you can't shift more than the number of bits in a long."
我的问题是,char是16位,byte是8位,short是16位,long是64位,但是
1) 为什么右边的 5 个低位将用于 char、byte 或 short 并且,
2)6右边的低位要用long?
谢谢!
意思是当像 1 << x
这样的表达式被求值时,只使用 x
的低位。 1 << x
等同于1 << (x & 0x1f)
,1L << x
等同于1L << (x & 0x3f)
.
1) why five low-order bits of the right-hand side will be used for char, byte or short and,
5 位意味着您可以移动从 0 到 2^5 - 1
= 31 的任意距离。比这更远的移动将意味着移动超过 int 的末尾。
2) six low-order bits of the right-hand side will be used for long?
6 位意味着您可以移动从 0 到 2^6 - 1
= 63 的任意距离。比这更远的移动意味着无论如何都要移动超过 long 的末尾。
例如:1 << 65 == 2
,因为只用到65的低五位,而65在二进制中是1000001
,所以低五位就是00001 == 1
和1 << 65 => 1 << 1 => 2
.
在思考 Java 时,有一个会话介绍了 Shift Operators,内容如下:
"If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you're operating on a long, you'll get a long result. Only the six low-order bits of the right-hand side will be used, so you can't shift more than the number of bits in a long."
我的问题是,char是16位,byte是8位,short是16位,long是64位,但是
1) 为什么右边的 5 个低位将用于 char、byte 或 short 并且,
2)6右边的低位要用long?
谢谢!
意思是当像 1 << x
这样的表达式被求值时,只使用 x
的低位。 1 << x
等同于1 << (x & 0x1f)
,1L << x
等同于1L << (x & 0x3f)
.
1) why five low-order bits of the right-hand side will be used for char, byte or short and,
5 位意味着您可以移动从 0 到 2^5 - 1
= 31 的任意距离。比这更远的移动将意味着移动超过 int 的末尾。
2) six low-order bits of the right-hand side will be used for long?
6 位意味着您可以移动从 0 到 2^6 - 1
= 63 的任意距离。比这更远的移动意味着无论如何都要移动超过 long 的末尾。
例如:1 << 65 == 2
,因为只用到65的低五位,而65在二进制中是1000001
,所以低五位就是00001 == 1
和1 << 65 => 1 << 1 => 2
.