简体   繁体   English

为什么Java使用这个长二进制数来使用Long.parseLong(String s,int radix)会冒犯?

[英]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 . 为什么Java认为这不是一个有效的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. 因为它超出了long的有效值范围。 The string: 字符串:

"-111111111111111111101011000000000000000000000000000000000000000"

should work just fine. 应该工作得很好。 You cannot specify a negative number directly in 2s complement binary notation . 您不能直接以2s补码二进制表示法指定负数。 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)). 如果你试图指定一个正数,那么这个数字太大而不适合Java long,这是一个以2s补码表示的带符号的64位值(这意味着它基本上是63位+一个符号位(它是一个比这更复杂,阅读2s页面上的补充))。

这是Java中的一个错误,请参阅http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269 ,他们将其修复为1.8

The long is stored in 2's compliment, but the parse method expects straight binary. long存储在2的补码中,但解析方法需要直接二进制。 So, the max number of digits in the String can be 63. 因此, String的最大位数可以是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 . 您可以传递一个长度为63的String ,并在其前面加上-如果您想要一个负long

Java long type: Java long类型:

8 bytes signed (two's complement). 签名8个字节(二进制补码)。 Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. 范围从-9,223,372,036,854,775,808到+9,223,372,036,854,775,807。

字符串的大小太长,请检查此问题

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. 这意味着只有63位,数字和一位代表正数或负数。 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 . 由于Long.parseLong()不能解析二进制补码中的数字,因此String是64位的正数,超过了long的最大正值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM