簡體   English   中英

需要對Java的32位整數表示系統進行說明嗎?

[英]clarification needed on Java's 32-bit integer representation system?

我需要一些有關Java(或其他任何語言)的二進制表示形式的說明。

請原諒,如果這太基本了,但是我需要徹底了解它。

x = 31 is represented in Java 32 bit as:

x — > 00000000 00000000 00000000 00011111  // 

the binary to decimal conversion is achieved by:
                               2^4+2^3+2^2+2^1+2^0=31

現在,如果您考慮所有打開的位,除了有signed bit (most significant bit) ,我們將得到

y -> 01111111 11111111 11111111 11111111

and binary to decimal conversion by summing powers of 2 will be:
        2^31+2^30………+2^3+2^2+2^1+2^0=4294967295.

但是,如果您這樣做:

System.out.println(Integer.parseInt("1111111111111111111111111111111",2));
you get: 2147483647 which is 2^31-1

所以這意味着,當打開31 bits時,我沒有得到2的冪的加和。這是為什么?

可能是我聽不懂某件事,如果有人可以澄清這一點會很有幫助。

如果這有幫助:直到31的所有這兩個提升能力都在此列表中:

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648]

編輯:我更正了y表示形式,現在它具有32位,但是如果您計算與冪加在一起就打開的31位,您將得到4294967295。我在python中有一個內襯

>>> reduce(lambda x,y: x+y, [pow(2,i) for i in range(32)])
4294967295

問題是在這里:

y -> 011111111 11111111 11111111 11111111

and binary to decimal conversion by summing powers of 2 will be:
        2^31+2^30………+2^3+2^2+2^1+2^0=4294967295.

您輸入了太多1。 正如喬恩·斯基特(Jon Skeet)在評論中提到的那樣,您應該只有31個1,而不是32。因此,總和應從2 ^ 30開始,而不是2 ^ 31。

更新 :嗯,您已經將該位更新為正確的1s數。盡管如此,我的總和聲明仍然成立。 它應從2 30開始,而不是2 31。

當您執行此部分時:

System.out.println(Integer.parseInt("1111111111111111111111111111111",2));
you get: 2147483647 which is 2^31-1

您有正確的1位數(31)。

所以這意味着,當打開31位時,我沒有得到2的冪的加和。

是的,您會做的-您得到2 0 + 2 1 + 2 2 + 2 3 + ... + 2 30 ...就是2 31-1 ,正如您所看到的。

沒有添加2 31,因為它將由32nd 1表示,這時您將超出int可以在Java中表示的范圍。

考慮較小的數字可能會更容易。 假設您有5位-前面的示例:

Integer.parseInt("11111")

就像您之前所說的那樣,它將打印出31,因為31是2 5-1

因此,對於全部設置為1的n位,您將得到2 n -1 ...對於您的示例(31位)是正確的。 這里沒有任何矛盾之處。

y -> 01111111 11111111 11111111 11111111
----------------------------------------
     31       23       15       7

該數字是每個字節中最高有效位的索引。

所以0x2^31 + 1x2^30 + 1x2^29 + ... + 1x2^0 = 2147483647

你只是太過分了。

你可以實際測試一下

int a = 0b01111111_11111111_11111111_11111111;
System.out.println(a);

版畫

2147483647

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM