【问题标题】:Java Base Conversion with addition带有加法的 Java 基础转换
【发布时间】:2013-09-26 01:55:04
【问题描述】:

10101base2 + 111base2 = 我该怎么做? 我已经知道如何将基础转换为另一个基础。 但是我将如何处理它们呢?

【问题讨论】:

  • 分别转换每个然后添加它们。
  • 数字就是数字——不管你用它们做什么。
  • 为什么要为自己添加另一个步骤并转换为十进制?只需将它们添加为二进制数(我假设您的最终结果也是二进制数)

标签: java addition base-conversion


【解决方案1】:

我发现 java 的 BigInteger 是其中最好的位操作。在其广泛的用途中(主要用于存储大量数字并支持其广泛的操作),您确实可以选择从 2 到 36 的基本转换。至于添加这些二进制数字,您可以使用他们提供的BigInteger.add(BigIntger)function。

示例:

BigInteger num_1=new BigInteger("10101",2);     //Store as Binary
BigInteger num_2=new BigInteger("111",2);       //Store as Binary
BigInteger result=num_1.add(num_2);

//Display the result using BigInteger.toString(int base)
System.out.println("Result = "+result.toString(10));    //Showing result in Decimal base here

当然,如果它有小数位,则使用William Gaul描述的方法。

【讨论】:

    【解决方案2】:
    int result = 0b10101 + 0b111;
    

    或者如果您的输入是字符串:

    int result = Integer.parseInt("10101", 2) + Integer.parseInt("111", 2);
    

    编辑:如果你问如何查看二进制形式的结果,还有这个:

    System.out.println(Integer.toBinaryString(result));
    

    【讨论】:

      猜你喜欢
      • 2013-10-22
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多