[英]Java parse int/long from binary literal string
Java wonderfully provides Long.decode
to parse most int formats, but not binary: Java出色地提供了Long.decode
来解析大多数int格式,但不解析二进制格式:
Long.decode("11") => 11
Long.decode("011") => 9
Long.decode("0x11") => 17
Long.decode("0b11") => java.lang.NumberFormatException
Is there a method that will parse a string containing a binary literal for me? 有没有一种方法可以为我解析一个包含二进制文字的字符串?
PS I understand if I wanted to extract the radix/value myself I could use the binary form of Long.parseLong
, but ideally what I'm looking for would be a function that could parse "0b11"
without any pre-processing. PS我知道如果我想自己提取基数/值,我可以使用Long.parseLong
的二进制形式,但是理想情况下,我要寻找的是一个无需任何预处理就可以解析"0b11"
的函数。
There is no way in the standard Java API. 标准Java API中没有办法。 However, I would take a look at Long.decode()
code and adapt it: 但是,我将看一下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;
}
That's as close as it can be to the original method (Ctrl+clicking core Java methods is a good experience). 这与原始方法尽可能接近(Ctrl +单击核心Java方法是一种很好的体验)。
Java doesn't seem to provide one; Java似乎没有提供一个。 however, is this code really that cumbersome that you need a library: 但是,此代码是否真的很麻烦,您需要一个库:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.