Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package arithmetic_coding;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- public class ArithmeticCoding {
- public static int ReadBits;
- public static int SentBits;
- public static void encode (String inFilename, String outFilename) {
- try {
- FileInputStream in = new FileInputStream (inFilename);
- FileOutputStream out = outFilename != null ?
- new FileOutputStream (outFilename) :
- null;
- double CharsOverall = 0.0,
- Length,
- Lower = 0.0,
- Upper = 10;
- int[] CharsCounter = new int[256];
- double[] Possibilities = new double[CharsCounter.length+1];
- int CurrentChar,
- Fillers = 0,
- Sent = 0;
- while ((CurrentChar = in.read ()) > -1)
- CharsCounter [CurrentChar]++;
- for (int Char : CharsCounter)
- CharsOverall += (double) Char;
- for (int i = 0; i < CharsCounter.length; i++)
- Possibilities [i+1] = Possibilities [i] + ((double) CharsCounter [i])/CharsOverall;
- in.close ();
- in = new FileInputStream (inFilename);
- while ((CurrentChar = in.read ()) > -1) {
- Length = Upper - Lower;
- Upper = Lower + Length * Possibilities [CurrentChar+1];
- Lower = Lower + Length * Possibilities [CurrentChar];
- if (Upper < 0.5) {
- Upper *= 2.0;
- Lower *= 2.0;
- Sent += send01s (out, Fillers);
- Fillers = 0;
- } else if (Lower >= 0.5) {
- Lower = (Lower - 0.5) * 2.0;
- Upper = (Upper - 0.5) * 2.0;
- Sent += send10s (out, Fillers);
- Fillers = 0;
- } else if (Lower >= 0.25 && Upper < 0.75) {
- Lower = (Lower - 0.25) * 2.0;
- Upper = (Upper - 0.25) * 2.0;
- Fillers++;
- }
- if (Lower == Upper) {
- System.out.println ("[fail]");
- }
- }
- // wyślij resztę
- } catch (IOException e) {
- e.printStackTrace ();
- }
- }
- private static int send01s (FileOutputStream out, int noOf1) {
- if (out != null)
- try {
- out.write (0);
- for (int i = 0; i < noOf1; i++)
- out.write (1);
- } catch (IOException e) {}
- return 1+noOf1;
- }
- private static int send10s (FileOutputStream out, int noOf0) {
- if (out != null)
- try {
- out.write (1);
- for (int i = 0; i < noOf0; i++)
- out.write (0);
- } catch (IOException e) {}
- return 1+noOf0;
- }
- }
Add Comment
Please, Sign In to add comment