class Test{
public static void main(String Args[]){
Integer x;
x = Integer.decode("0b111");
System.out.println(x);
}
}
这不适用于二进制的前缀0和前缀为0的八进制。 这样做的正确方法是什么?
答案 0 :(得分:5)
查看Integer.decode
的文档,我看不出二进制 应该工作的迹象。八进制应该可以工作,前缀只有0:
System.out.println(Integer.decode("010")); // Prints 8
您可以像这样处理“0b”的二进制指示符:
int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
完整示例代码,显示15:
的二进制,八进制,十进制和十六进制表示public class Test {
public static void main(String[] args) throws Exception {
String[] strings = { "0b1111", "017", "15", "0xf" };
for (String string : strings) {
System.out.println(decode(string)); // 15 every time
}
}
private static int decode(String text) {
return text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
}
}
答案 1 :(得分:0)
Integer.decode无法解析二进制文件,请参阅API。但八进制工作正常,例如:
int i = Integer.decode("011");
答案 2 :(得分:0)
从Java 7开始,您可以直接在代码中使用binary literals。但请注意,这些类型为byte
,short
,int
或long
(以及不 String
)。
int x = 0b111;