Sebastjan
Sebastjan

Reputation: 71

Trouble converting binary to text

I have to convert binary data into text and I think I'm close, but something's not working quite right. In this case the output is supposed to be the letters "FRI", but I get a bunch of other symbols surrounding the letters: F2eÊ)R¤I$I$I. I don't know what seems to be the problem. This is the code:

public class DN06 {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    String location = "D:\\NetBeans\\Projects\\DN06\\src\\datoteka1.txt";
    File newFile = new File(location);
    Scanner sc = new Scanner(newFile);
    StringBuilder sb = new StringBuilder();
    String drek = "";
    try{
        while (sc.hasNext()){
            String content = new String(sc.next().getBytes(),"UTF-8");
            for (int i=0;i<=content.length()-8;i++){
                int charCode = Integer.parseInt(content.substring(i,i+8),2);
                drek += new Character((char)charCode).toString();
            }
            System.out.println(drek);
        }
    }catch( UnsupportedEncodingException e){
        System.out.println("Unsupported character set");
    }
}

}

Upvotes: 2

Views: 260

Answers (1)

Absent
Absent

Reputation: 914

In the line

String content = new String(sc.next().getBytes(),"UTF-8");

You already have your desired output. Here you already parsed the byte array you got to a String with the encoding UTF-8. After that you tried to decode it again into UTF-8 and hence you got a wrong result.

Edit:

Since the content of your File is written in binary, this will not be enough, you will have to parse every byte once. The problem in your for loop is, that you move the i always just one digit instead of 8 digits to the right in the binary string.

for (int i=0;i<=content.length()-8;i = i+8)

This should do the job, for real this time

Upvotes: 3

Related Questions