問題描述
我正在嘗試將幾個二進制字符串轉換回 int.但是它不會轉換我所有的二進制字符串,給我留下一個 java.lang.NumberFormatException 異常.這是我的帶有 3 個二進制字符串的測試代碼:
I'm trying to convert a couple of binary strings back to int. However it doesn't convert all my binary strings, leaving me a java.lang.NumberFormatException exception. Here is my test code with 3 binary string:
public class Bin {
public static void main(String argvs[]) {
String binaryString ;
binaryString = Integer.toBinaryString(~0);
//binaryString = Integer.toBinaryString(~1);
//binaryString = "1010" ;
int base = 2;
int decimal = Integer.parseInt(binaryString, base);
System.out.println("INPUT=" + binaryString + " decimal=" + decimal) ;
}
}
如果我轉換1010"效果很好,但是當我嘗試轉換另外兩個之一時,我得到了異常.有人可以向我解釋這是為什么嗎?
If I convert the "1010" it works great, but when I try to convert one of the other two I get the exception. Can someone explain to me why this is ?
干杯
推薦答案
來自 http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString(int) :toBinaryString()
方法將其輸入轉換為無符號整數值是參數加上 232 如果參數為負數"的二進制表示.
From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString(int) : the toBinaryString()
method converts its input into the binary representation of the "unsigned integer value is the argument plus 232 if the argument is negative".
來自 http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) :parseInt()
方法拋出 NumberFormatException
如果字符串表示的值不是 int
類型的值".
From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) : the parseInt()
method throws NumberFormatException
if "The value represented by the string is not a value of type int
".
注意~0
和~1
都是負數(分別為-1和-2),所以會轉換成232的二進制表示-1 和 232-2 分別不能用 int
類型的值表示,所以導致 NumberFormatException
你所看到的.
Note that both ~0
and ~1
are negative (-1 and -2 respectively), so will be converted to the binary representations of 232-1 and 232-2 respectively, neither of which can be represented in a value of type int
, so causing the NumberFormatException
that you are seeing.
這篇關于java:將二進制字符串轉換為int的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!