2017-03-02 156 views
0

我想將.hex文件中的字符符號轉換爲字節數組。我正在使用此代碼,但結果與我的文件中的符號不​​同。如何將十六進制文件轉換爲二進制數組Android,Java

我的代碼:

public byte[] getResource(int id, Context context) throws IOException { 
    Resources resources = context.getResources(); 
    InputStream is = resources.openRawResource(id); 

    ByteArrayOutputStream bout = new ByteArrayOutputStream(); 

    byte[] readBuffer = new byte[2 * 1024 * 1024]; 
    byte[] data; 

    try { 
     int read; 
     do { 
      read = is.read(readBuffer, 0, readBuffer.length); 
      if (read == -1) { 

       break; 


      } 
      String hex = new String(readBuffer); 
      data = hexStringToByteArray(hex); 
      bout.write(data); 
      // bout.write(readBuffer, 0, read); 
     } while (true); 

     return bout.toByteArray(); 
    } finally { 
     is.close(); 
    } 
} 

public static byte[] hexStringToByteArray(String s) { 
    int len = s.length(); 
    byte[] data = new byte[len/2]; 
    for (int i = 0; i < len; i += 2) { 
     data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) 
       + Character.digit(s.charAt(i + 1), 16)); 
    } 
    return data; 
} 

首先從3個我.hex文件行

:020000040800F2 :20000000103C0020650200081502000817020008190200081B0200081D0200080000000056 :200020000000000000000000000000001F020008210200080000000023020008714A00087C

但是當我檢查結果數組,我看到: -16,32,0,0,64,-128,15,31,-17,32,0,0,0,16,60,0,32,101,2,0,8 ,21 ...

我的錯誤在哪裏?請給我正確的方式!

+0

如果你有一個*文本*文件,你應該逐行閱讀文本和一個'Reader'。注意你的文件的每一行顯然是以冒號開頭的,但是你現在將它當作十六進制數字處理。 –

+0

@JonSkeet謝謝您的評論,但是您能否解釋一下請 – MrStuff88

+0

好吧,您的代碼正在讀取文件,就好像它是一個二進制文件,從InputStream讀取並手動將字節轉換爲字符串。你的文件似乎是按行組織的,所以你爲什麼不用「BufferedReader」逐行閱讀?然後,你需要修剪每一行的冒號... –

回答

1

首先從文件中讀取所有數據,並從字符串中刪除所有不正確的符號,例如(':'),如@pitfall所示並存儲在字符串中,然後執行以下操作。

String s="yourStringFromFile"; 
byte[] b = new BigInteger(s,16).toByteArray(); 
0

您應該從十六進制字符串中刪除所有不正確的符號(如':')。

hexStringToByteArray( 「:020000040800F」) - > [-16,32,0,0,64,-128,15] hexStringToByteArray( 「020000040800F2」) - > [2,0,0,4,8, 0,-14]

相關問題