2014-03-13 15 views
0

我想編一個具有將二進制數更改爲小數的函數的代碼。有關在JAVA中輕鬆「返回」的問題

所以我做了衆長tonum()

,並試圖在Main方法返回。

但屏幕上顯示任何內容。哪裏有問題? Plz給了我一些提示。

public class Bitmap { 
     byte[] byteArr; //byte array for saving 0 or 1 
     char[] charArr; //char array for casting from string to byte array 

    public static void main(String[] args) throws Exception { 
      Bitmap test1 = new Bitmap("100110"); 
      test1.tonum();    
     } 
    public Bitmap(String val) throws Exception { 
       byteArr = new byte[val.length()]; //To make the array length of Bitmap should e same as that of string 
       charArr = val.toCharArray();  //casting from string to char 

       for(int i = 0; i < charArr.length; i++) { 
       if (charArr[i] == '0') 
        byteArr[i] = 0; 
       else if (charArr[i] == '1') 
        byteArr[i] = 1; 
       else throw new Exception("Bitmap are should be sequences of zeros and ones!"); 
       } 
      } 

    public long tonum() { 
     int temp = 0; 
     String str = ""; 
     String str2 = ""; 
     for (int i = 0; i < this.byteArr.length; i++){ 
      temp = this.byteArr[i]; 
      str = Integer.toString(temp); 
      str2 = str2 + str; 
     } 
     long decimal = (long)Integer.parseInt(str2,10); 
     System.out.println(str2); 
     return decimal; 
    } 
} 
+1

這是什麼語言?請相應標記。 – geoffspear

回答

0
 long decimal = (long)Integer.parseInt(str2,10); 

不改變二進制爲十進制。它將十進制更改爲二進制。而且你首先沒有小數,你有一個字符串或二進制表示。嘗試一個2的基數。但是當你所做的只是解構和重建原始字符串時,爲什麼你同時擁有一個字符數組和字節數組是任何人的猜測。