2016-04-11 3 views
1

私は、文字列とそれにコード化された2進数を含むバイトが続くファイルを持っています。javaの文字列を含むファイルからバイトをデコードする方法は?

Thisisastring. �J 

私のコードでは、文字列を無視し、スペースで区切られたバイトのデコードに焦点を当てます。私がコードを実行すると、最初の2進数が多く離れていることを除いて結果は正しいようです。

StringBuffer buffer = new StringBuffer(); 
    File file = new File(arg); 
    FileInputStream in = new FileInputStream(file); 
    InputStreamReader isr = new InputStreamReader(in, "UTF8"); 
    Reader inn = new BufferedReader(isr); 
    int ch; 

    while ((ch = inn.read()) > -1){ 
     buffer.append((char)ch); 
    } 

    inn.close(); 

    String content = buffer.toString(); 
    String temp = new String(); 
    for(int i=0; i<content.length(); i++){ 
     temp += content.charAt(i); 
     if(content.charAt(i) == ' '){ 
      while(i != content.length()-1){ 
       i++; 
       byte b = (byte) content.charAt(i); 
       String x = Integer.toString(b & 0xFF, 2); 
       System.out.println(x); 
      } 
     } 
    } 

結果:

11111101 <- Why is only this one incorrect? 
11000 
1001010 
1011 

期待されているもの:

10010101 
00011000 
01001010 
1011 

答えて

1

あなたは、バイナリデータのためReadersまたはStringsを使用しないでください。

StringBuffer buffer = new StringBuffer(); 
File file = new File(arg); 
FileInputStream in = new FileInputStream(file); 
DataInputStream dis = new DataInputStream(new BufferedInputStream(in)); 
int ch; 

while ((ch = din.read()) > -1){ 
    buffer.append((char)ch); 
    if (ch == ' ') 
    { 
     // next byte is a binary value 
     byte b = din.readByte(); 
     String x = Integer.toString(b & 0xFF, 2); 
     System.out.println(x); 
    } 
} 
関連する問題