首页 文章

使用基本数学运算符将二进制字符串转换为整数

提问于
浏览
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的新手,我的朋友建议使用整数方法,这是有效的 . 但是,使用基本运算符(例如逻辑,算术等)转换最有效的方法

2 回答

  • 0

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

    正确:

    • 它有效,并且

    • 这是最好的方式 .

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

    • 如果您不熟悉Java,那么您不应该过分关注代码的效率 . 你没有直觉 .

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

    • 即使这是您应用程序中的性能热点, Integer.parseint 代码(毫无疑问)已经得到了很好的优化 . 使用"primitive"操作可以做得更好 . (在幕后,这些方法已经在做你想做的事了 . )


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

  • 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

相关问题