11 Long.decode("011") => 9 Long.d-6ren">
gpt4 book ai didi

Java从二进制文字字符串中解析int/long

转载 作者:行者123 更新时间:2023-11-30 02:38:06 26 4
gpt4 key购买 nike

Java 奇妙地提供了 Long.decode 来解析大多数 int 格式,但不是二进制:

Long.decode("11") => 11
Long.decode("011") => 9
Long.decode("0x11") => 17
Long.decode("0b11") => java.lang.NumberFormatException

有没有一种方法可以为我解析包含二进制文字的字符串?

附注我知道如果我想自己提取基数/值,我可以使用 Long.parseLong 的二进制形式,但理想情况下我正在寻找的是一个可以解析 "0b11 的函数“无需任何预处理。

最佳答案

标准 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 方法是一种很好的体验)。

关于Java从二进制文字字符串中解析int/long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42570502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com