Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

java - Why is 1 plus 31 zeros not a valid integer, if bit flags are 31 length, plus one negative/positive flag?

According to this, in the around-fourth paragraph below the first table, says

In general, we will use an integer to represent a set on a domain of up to 32 values (or 64, using a 64-bit integer), with a 1 bit representing a member that is present and a 0 bit one that is absent.

If that's true, then why does this 32 digit binary number exceed Integer.MAX_VALUE?

System.out.println(Integer.parseInt("10000000000000000000000000000000", 2));

Error:

Exception in thread "main" java.lang.NumberFormatException: For input string: 
"10000000000000000000000000000000"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Test.main(Test.java:10)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In base 2, 10000000000000000000000000000000 (that's 31 zeroes) is 2^31. A Java int is a 32-bit twos complement representation of numbers between -2^31 and 2^31-1; and this range of course does not include 2^31. That's why this value can't be converted to an int - although a long would be fine.

If you have a Java int whose bits are 10000000000000000000000000000000 (still 31 zeroes), that's -2^31.

It's not true that the first bit of a Java int is a positive/negative flag. It's simply a digit with place value of -2^31.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...