2014-04-24 89 views
0

我在這裏搜索了一段時間,似乎沒有什麼能幫助我完成我的任務。我試圖手動轉換一個int數組,其中包含二進制代碼,執行十進制轉換,然後將其轉換爲char來獲取ascii等效項。我有一些東西已經開始了,但是當我打印出來時,我得到了-591207182作爲信息,這顯然是不正確的。我的計劃在下面。我在編寫和理解Java方面相當新手,因此非常感謝最高效和易於理解的路線。在Java中將二進制詮釋數組轉換爲ASCII碼

class DecodeMessage 
{ 
    public void getBinary(Picture secretImage) 
    { 
    Pixel pixelObject = null; 
    Color pixelColor = null; 
    int [] binaryInt = new int[secretImage.getWidth()]; 
    int x = 0; 


     int redValue = 0; 
     while(redValue < 2) 
     {   
      Pixel pixelTarget = new Pixel(secretImage,x,0); 
      pixelColor = pixelTarget.getColor(); 
      redValue = pixelColor.getRed(); 
      binaryInt[x] = redValue; 
      x++; 
     } 
    } 
     public void decodeBinary(int [] binary) 
     { 
     int binaryLen = binary.length; 
     long totVal = 0; 
     int newVal = 0; 
     int bitVal = 0; 
     long preVal = 0; 
     long base = 2; 

     for(int x = binaryLen - 1; x >= 0; x--) 
     { 
      bitVal = binary[x]; 
      preVal = bitVal * base; 
      totVal += preVal; 
      base = base * 2; 
     } 

     System.out.println(totVal); 
    } 
} 
public class DecodeMessageTester 
{ 
    public static void main(String[] args) 
    { 
     Picture pictureObj = new Picture("SecretMessage.bmp"); 
     pictureObj.explore(); 
     DecodeMessage decode = new DecodeMessage(); 
     decode.getBinary(pictureObj); 
     int[] bitArray = {0,1,1,0,0,0,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1}; 
     decode.decodeBinary(bitArray); 
    } 
} 
+0

轉換成char的位置在哪裏? – tbodt

+0

嘗試'String decimalString = new BigInteger(「0010」,2).toString(10));'二進制的小數。 – Braj

回答

0

你的問題是你試圖把所有的48位壓縮到一個int。但是,如http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html所述,Java中的int只能保存32位,因此您的數字會溢出。嘗試更改base,preValtotVallong,它可以保存64位。

當然,如果你需要超過64位(或63位,因爲最後一位是符號位),你將無法使用原始數字數據類型來保存它。

+0

這有一點幫助,現在,而不是一個負值......當終端窗口打印它時,我現在有216409925936370。 –

相關問題