java - 精确的二进制求和

标签 java binary

我使用以下代码进行二进制求和:

class dump{
public static void main(String[] args){
    final int number0 = Integer.parseInt("000", 2);
    final int number1 = Integer.parseInt("1", 2);

    final int sum = number0 + number1;
    System.out.println(Integer.toBinaryString(sum));

}
}

问题是我没有得到答案的精确精度 - 例如 000 + 1 或 00 + 1 都解析为 1。
由于我打算使用结果作为 hashmap 中的键,因此结果的非唯一性是一个问题。
如何获得 00+1=>01 或 000+1 =>001。

最佳答案

The problem is that I do not get the exact precision of the answer

无关紧要的前导零对答案的精度没有影响:答案 100100000000000001 完全相同 - 它是相同的数字。

Since I intend to use the result as the key in a hashmap ,the non-uniqueness of the result is a problem.

如果您要使用这样的字符串作为排序映射中的键,则会出现问题,因为键有时会出现乱序。在 HashMap 中,这不是问题,因为 Integer.toBinaryString(sum) 会删除所有数字中的前导零,因此您永远不会看到像 000 这样的数字你的程序。如果这些数字确实来自外部,您可以在将它们用作哈希键之前通过解析并转换为二进制来标准化它们。

关于java - 精确的二进制求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18403592/

相关文章:

java - 尝试更新 src/web/prod 文件夹(jsp)中的文件

java - NotImplementedException 是内部专有 API

c - 将文件表示为方程式?

java - 如何有效地将 BitSet 转换为二进制字符串?

.net - PDF比较检查

Erlang 二进制模式匹配未知数量

java - 如何使 Java 线程获得相当数量的 CPU 时间

java - 在 Eclipse 中匹配正则表达式环视

java - 如何使用 FileInputStream 将音频文件读入具有 2 字节数据的数组

python - 如何将二进制代码解码为文本?