user2163684
user2163684

Reputation: 31

How to compress a string of 0s and 1s in java

I am doing Huffman Coding right now and I ran into this bump in the road. I have pretty much everything done but this one part. My main issue right now is I am not sure how to store my binary string of 0s and 1s that is encoded using my code. I try just writing it out normally but the file size of that ends up being much bigger then the original text file that I encoded. Can someone give me any ideas of how I should store my binary strings so that this don't happen.

Update I have notice that a lot of char is not recognized when I try to cast it to a char and ends up being printed out as ?s and when I do

String u = scanner.nextLine();
    char l;
    for(int b = 0;b<u.length();b++)
    {
    l = u.charAt(b);
    int c = (int) u.charAt(b);
    String p = Integer.toBinaryString(c);

    if(b!= u.length()-1)
    {
    while(p.length()!=8){
        p = "0" + p;
    //Thread.sleep(3000);
    }
    }System.out.println(p);
    k.append(p);

it reads in the ? and print out 00111111. Anyone has any suggestions of how I can fix this?

Upvotes: 0

Views: 2966

Answers (1)

Stephan Heijl
Stephan Heijl

Reputation: 464

When you are storing the binary string it is just that, a String. One way of storing them more efficiently is converting the binary string to integers and using these to store the string as ASCII characters.

  1. Cut the string into short pieces of 8 characters each (1 byte = 8 bits)
  2. Use Integer.parseInt(piece, 2); to convert the binary piece into an int
  3. Now cast the integer to a char
  4. Repeat this for every piece of the binary string.

You then join up the chars into a string and store the result as a plain text file. This should result in file that is 8x smaller than your previous binary string file.

[EDIT] This is working en and decoding code that has been tested under a variety of circumstances. http://pastebin.com/Tq3nKX8A Please use it as you see fit.

Upvotes: 2

Related Questions