Java奇妙地提供Long.decode
来解析大多数int格式,但不解析二进制:
Long.decode("11") => 11
Long.decode("011") => 9
Long.decode("0x11") => 17
Long.decode("0b11") => java.lang.NumberFormatException
是否有一种方法可以解析包含二进制文字的字符串?
P.S。
我理解,如果我想自己提取基数/值,我可以使用Long.parseLong
的二进制形式,但理想情况下,我正在寻找的是一个可以解析"0b11"
而不需要任何前置的函数 - 处理。
答案 0 :(得分:2)
标准Java API中没有办法。但是,我会查看Long.decode()
代码并对其进行修改:
public static Long decode(String nm) throws NumberFormatException {
int radix = 10;
int index = 0;
boolean negative = false;
Long result;
if (nm.length() == 0)
throw new NumberFormatException("Zero length string");
char firstChar = nm.charAt(0);
// Handle sign, if present
if (firstChar == '-') {
negative = true;
index++;
} else if (firstChar == '+')
index++;
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
/// >>>> Add from here
else if (nm.startsWith("0b", index) || nm.startsWith("0B", index)) {
index += 2;
radix = 2;
}
/// <<<< to here
else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
}
else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
if (nm.startsWith("-", index) || nm.startsWith("+", index))
throw new NumberFormatException("Sign character in wrong position");
try {
result = Long.valueOf(nm.substring(index), radix);
result = negative ? Long.valueOf(-result.longValue()) : result;
} catch (NumberFormatException e) {
// If number is Long.MIN_VALUE, we'll end up here. The next line
// handles this case, and causes any genuine format error to be
// rethrown.
String constant = negative ? ("-" + nm.substring(index))
: nm.substring(index);
result = Long.valueOf(constant, radix);
}
return result;
}
尽可能接近原始方法(Ctrl +单击核心Java方法是一种很好的体验)。
答案 1 :(得分:0)
Java似乎没有提供一个;但是,这段代码真的很麻烦,你需要一个库:
public static Long parseBinaryLiteral (String s)
{
if (s == null)
throw new NumberFormatException("null");
// no need to check 0B
s = s.toLowerCase();
String p = "";
if (s.startsWith("0b"))
p = s.substring(2);
else if (s.startsWith("-0b"))
p = "-" + s.substring(3);
else if (s.startsWith("+0b"))
p = s.substring(3);
else
throw new NumberFormatException("For input string: \"" + s + "\"");
return Long.parseLong(p, 2);
}