用Java长时间移位 [英] Bitshifting a long in Java
问题描述
对于任何人来说,这都是一件容易的事!
Im sure this is an easy one for whoever sees it first!
为什么在Java中代码类似
Why in Java does code like
long one = 1 << 0;
long thirty = 1 << 30;
long thirtyOne = 1 << 31;
long thirtyTwo = 1 << 32;
System.out.println(one+" = "+Long.toBinaryString(1 << 0));
System.out.println(thirty+" = "+Long.toBinaryString(1 << 30));
System.out.println(thirtyOne+" = "+Long.toBinaryString(1 << 31));
System.out.println(thirtyTwo+" = "+Long.toBinaryString(1 << 32));
打印
1 = 1
1073741824 = 1000000000000000000000000000000
-2147483648 = 1111111111111111111111111111111110000000000000000000000000000000
1 = 1
这对我来说没有意义. long
是一个64位数字-而在上面它的作用类似于int
.我知道移位的byte
会进行int提升,但是在这种情况下我看不到发生了什么.
This does not make sense to me. long
is a 64 bit number - whereas it seems to act like an int
in the above. I know bitshifted byte
s undergo int promotion but I dont see whats going on in this case.
任何有关这里发生的事情的指针都将是不错的:)
Any pointers on whats going on here would be good :)
Thx
编辑:感谢您提供所有答案-单击提交"后,我意识到发生了什么,但是我进入了readonly
模式,因此无法删除!非常感谢!
EDIT: thanks for all the answers - i realised what was going on as soon as I clicked 'submit' but SO went into readonly
mode and I couldnt delete! Many thanks!
推荐答案
这是因为1是int
文字,因此<<
应用于整数.结果被强制转换为long
,但那时为时已晚.
It's because 1 is an int
literal, so <<
is applied to an integer. The result is cast to a long
, but by then it's too late.
如果您写1L<< 32,等,那么一切都会好起来的. L
用于表示long
文字.
If you write 1L << 32, etc., then all will be well. L
is used to denote a long
literal.
这篇关于用Java长时间移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!