使用Integer.parseInt转换32位二进制字符串失败 [英] Converting 32-bit binary string with Integer.parseInt fails

查看:1008
本文介绍了使用Integer.parseInt转换32位二进制字符串失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这部分代码失败:

Why does this part of code fail:

Integer.parseInt("11000000000000000000000000000000",2);

Exception in thread "main" java.lang.NumberFormatException: For input string: "11000000000000000000000000000000"

据我所知,Integer是32位值。上面代码中的0和1的数量是32.如果有31个代码可以工作。为什么会这样?

As far as I understand Integer is a 32 bit value. The number of zeros and ones in the upper code is 32. If there are 31 the code works. Why is that so?

推荐答案

您的代码失败,因为它试图解析一个需要33位作为签名存储的数字整数。

Your code fails because it tries to parse a number that would require 33 bits to store as a signed integer.

带符号的 int 是二进制补码表示的32位值,其中第一位表示数字的符号,以及剩余的31位数字的值。 (-ish。)Java只支持有符号整数,而 parseInt()和朋友不应该解析两个补码位模式 - 从而解释 1 或(可能暗示) 0 在右边第32个位置作为标志。它们的目的是支持解析人类可读的再现,这是一个可选的 - (或 + )符号,后跟数字的绝对值。

A signed int is a 32 bit value in two's complement representation, where the first bit will indicate the sign of the number, and the remaining 31 bits the value of the number. (-ish.) Java only supports signed integers, and parseInt() and friends aren't supposed to parse two's complement bit patterns – and thus interpret the 1 or (possibly implied) 0 at the 32nd position from the right as the sign. They're meant to support parsing a human-readable reprentation, which is an optional - (or +) for the sign, followed by the absolute value of a number.

在这种情况下,这是一种错误的直觉,导致你期望你描述的行为:如果你正在解析除了基数2之外的任何其他基数(或者可能是其他常用的二次幂基数),您是否希望输入的第一个数字影响符号?显然你不会;拥有,比方说, parseInt(2147483648)返回 -2147483648 按设计将是PHP级别的疯狂。

In this context, it's a false intuition that leads you to expect the behaviour you describe: if you were parsing any other base besides base 2 (or maybe the other commonly used power-of-two bases), would you expect the first digit of the input to affect the sign? Obviously you wouldn't; having, say, parseInt("2147483648") return -2147483648 by design would be PHP levels of crazy.

特殊套管两个基数也感觉很奇怪。最好采用单独的方法来处理位模式,例如此答案中的方法。

Special-casing power-of-two bases also feels odd. Better to have a separate approach to handling bit patterns, for example the one in this answer.

这篇关于使用Integer.parseInt转换32位二进制字符串失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆