当前位置: 动力学知识库 > 问答 > 编程问答 >

Why is Java offended by my use of Long.parseLong(String s, int radix) with this long binary number?

问题描述:

I have the following code:

Why does Java think that this is not a valid long.

@Test

public void testOffendingBinaryString() {

String offendingString = "1000000000000000000010101000000000000000000000000000000000000000";

assertEquals(64, offendingString.length());

Long.parseLong(offendingString, 2);

}

网友答案:

Because it's out of range for the valid value of a long. The string:

"-111111111111111111101011000000000000000000000000000000000000000"

should work just fine. You cannot specify a negative number directly in 2s complement binary notation. And if you're trying to specify a positive number, that number is too big to fit into a Java long, which is a signed 64-bit value expressed in 2s complement (which means it's basically 63 bits + a sign bit (it's a little more complicated than that, read the page on 2s complement)).

网友答案:

The long is stored in 2's compliment, but the parse method expects straight binary. So, the max number of digits in the String can be 63.

When using regular binary, there is no sign bit. You can pass it a String with length 63 and precede it with a - if you want a negative long.

网友答案:

Java long type:

8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

网友答案:

The size of the string is too long, check this question

网友答案:

Internally numbers are represented using the Two's complement. That means there are only 63 bits, for the number and one bit to represent positive or negative numbers. Since Long.parseLong() is not ment to parse numbers in Two's complement your String is a positive number with 64 bits, that exceeds the maximum positive value for a long.

网友答案:

This is a bug in Java, see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269, they fixed it in 1.8

分享给朋友:
您可能感兴趣的文章:
随机阅读: