0

主要的:

public class Main{                                      
  public static void main(String[] args){                                       
    System.out.println(Convert.BtoI("10001"));                                  
    System.out.println(Convert.BtoI("101010101"));                                              
  }                                     
}

班级:

public class Convert{                                       
  public static int BtoI(String num){                                       
    Integer i= Integer.parseInt(num,2);                                     
    return i;                                       
  }                                     
}

因此,我正在研究转换器,因为我是 Java 新手,所以我很挣扎,我的朋友建议使用整数方法,该方法有效。但是,使用基本运算符(例如逻辑、算术等)转换哪种方法最有效?

4

2 回答 2

1

....我的朋友建议使用整数方法,它有效。

正确的:

  • 它有效,并且
  • 这是最好的方法。

但是,使用基本运算符(例如逻辑、算术等)转换哪种方法最有效?

  • 如果您是 Java 新手,那么您不应该沉迷于代码的效率。你没有直觉。

  • 即使您有经验,您也可能不应该优化它。在大多数情况下,小规模的效率是无关紧要的,你最好在开始优化之前使用分析器来验证你对什么是重要的直觉。

  • 即使这是您的应用程序中的性能热点,Integer.parseint代码(毫无疑问)已经得到了很好的优化。使用“原始”操作可以做得更好的可能性很小。(在幕后,这些方法很可能已经在做与您正在做的事情相同的事情。)


如果您只是因为好奇而问这个问题,请查看Integer该类的源代码。

于 2018-12-10T01:05:36.460 回答
0

如果您想使用基本算术将二进制数转换为整数,则可以将 Convert 类中的 BtoI() 方法替换为以下代码。

public static int BtoI(String num){                                       
        int number = 0; // declare the number to store the result
        int power = 0; // declare power variable

        // loop from end to start of the binary number
        for(int i = num.length()-1; i >= 0; i--)
        {
            // check if the number encountered is 1
            /// if yes then do 2^Power and add to the result
            if(num.charAt(i) == '1')
                number += Math.pow(2, power);
            // increment the power to use in next iteration
            power++;
        }
        // return the number
        return number;
      }  

在上面的代码中执行正常计算以获得结果。例如 101 => 1*2^2 + 0 + 1*2^0 = 5

于 2018-12-10T00:39:17.293 回答