[英]Long getting treated as 32 bits in Java?
我正在嘗試運行以下代碼,
public class MyClass {
public static void main(String args[]) {
long x = 1 << 39;
long l = 537150415L;
l = l | x;
System.out.println(x);
System.out.println(l);
}
}
這輸出,
128
537150415
我期望x
很大。 128
看起來像2^7
,即2^(39-32)
。 但是我認為長是64位。
我正在嘗試設置一組數字。 數字可以在1-60之間。
JDoodle鏈接 - [https://www.jdoodle.com/online-java-compiler#&togetherjs=uH49U5c4Ej]
您需要使用1L
而不是1
來將1
表示為字面量long
:
long x = 1L << 39;
long l = 537150415L;
l = l | x;
System.out.println(x);
System.out.println(l);
問題是1 << 39
是32位表達式。 所以
long x = 1 << 39;
首先計算一個32位的值,然后將符號擴展為分配的64位值。
如果要創建64位掩碼,請使用1L << 39
。
java的問題是int
是c ++中的int32_t
,而long
是int64_t
,沒有未簽名的類型。
這意味着您必須考慮到二進制補碼,因此,當高位被設置時,您具有-2 ^ 64。
如果只關心位集,則不應該直接打印長整數。 做這樣的事情:
for (int i = 0; i < 64; i++) {
System.out.println((l & (1 << i)) != 0 ? "Bit " + i + " is set" : "Bit " + i + " is not set");
}
編輯:好的,雖然這不是問題,但為了完整起見,我將保留答案(因為這些確實是要考慮的陷阱)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.