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

查看:40
本文介绍了使用 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 之外的任何其他基数(或者可能是其他常用的 2 的幂)基数),您认为输入的第一个数字会影响符号吗?显然你不会;比方说,parseInt("2147483648") return -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.

特殊外壳的 2 次幂也感觉很奇怪.最好采用单独的方法来处理位模式,例如 this answer 中的方法.

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天全站免登陆