Guest User

Untitled

a guest
Jan 22nd, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. package arithmetic_coding;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6.  
  7. public class ArithmeticCoding {
  8. public static int ReadBits;
  9. public static int SentBits;
  10.  
  11. public static void encode (String inFilename, String outFilename) {
  12. try {
  13. FileInputStream in = new FileInputStream (inFilename);
  14. FileOutputStream out = outFilename != null ?
  15. new FileOutputStream (outFilename) :
  16. null;
  17.  
  18. double CharsOverall = 0.0,
  19. Length,
  20. Lower = 0.0,
  21. Upper = 10;
  22.  
  23. int[] CharsCounter = new int[256];
  24.  
  25. double[] Possibilities = new double[CharsCounter.length+1];
  26. int CurrentChar,
  27. Fillers = 0,
  28. Sent = 0;
  29.  
  30.  
  31. while ((CurrentChar = in.read ()) > -1)
  32. CharsCounter [CurrentChar]++;
  33. for (int Char : CharsCounter)
  34. CharsOverall += (double) Char;
  35.  
  36. for (int i = 0; i < CharsCounter.length; i++)
  37. Possibilities [i+1] = Possibilities [i] + ((double) CharsCounter [i])/CharsOverall;
  38.  
  39.  
  40. in.close ();
  41. in = new FileInputStream (inFilename);
  42.  
  43. while ((CurrentChar = in.read ()) > -1) {
  44. Length = Upper - Lower;
  45. Upper = Lower + Length * Possibilities [CurrentChar+1];
  46. Lower = Lower + Length * Possibilities [CurrentChar];
  47.  
  48. if (Upper < 0.5) {
  49. Upper *= 2.0;
  50. Lower *= 2.0;
  51.  
  52. Sent += send01s (out, Fillers);
  53. Fillers = 0;
  54. } else if (Lower >= 0.5) {
  55. Lower = (Lower - 0.5) * 2.0;
  56. Upper = (Upper - 0.5) * 2.0;
  57.  
  58. Sent += send10s (out, Fillers);
  59. Fillers = 0;
  60. } else if (Lower >= 0.25 && Upper < 0.75) {
  61. Lower = (Lower - 0.25) * 2.0;
  62. Upper = (Upper - 0.25) * 2.0;
  63.  
  64. Fillers++;
  65. }
  66.  
  67. if (Lower == Upper) {
  68. System.out.println ("[fail]");
  69. }
  70. }
  71.  
  72. // wyślij resztę
  73. } catch (IOException e) {
  74. e.printStackTrace ();
  75. }
  76. }
  77.  
  78. private static int send01s (FileOutputStream out, int noOf1) {
  79. if (out != null)
  80. try {
  81. out.write (0);
  82. for (int i = 0; i < noOf1; i++)
  83. out.write (1);
  84. } catch (IOException e) {}
  85.  
  86. return 1+noOf1;
  87. }
  88.  
  89. private static int send10s (FileOutputStream out, int noOf0) {
  90. if (out != null)
  91. try {
  92. out.write (1);
  93. for (int i = 0; i < noOf0; i++)
  94. out.write (0);
  95. } catch (IOException e) {}
  96.  
  97. return 1+noOf0;
  98. }
  99. }
Add Comment
Please, Sign In to add comment