-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoding.java
More file actions
executable file
·74 lines (70 loc) · 2.21 KB
/
coding.java
File metadata and controls
executable file
·74 lines (70 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.BitSet;
import java.io.*;
import java.lang.Number;
import java.lang.Math;
import java.math.BigInteger;
class coding
{
public static void encode(String code, String filename) throws IOException
{
FileOutputStream out = new FileOutputStream(filename);
int nbytes = (int)Math.ceil(code.length()/8.0);
int last = code.length()%8;
//System.out.println(last);
out.write(last);
int start = 0;
int stop = start + 8;
for (int i=0; i<nbytes; i++)
{
String s = code.substring(start, stop);
start += 8;
if (i == nbytes-2)
stop = code.length();
else
stop +=8;
out.write(Integer.parseInt(s, 2));
}
out.close();
}
public static String decode(String filename) throws IOException
{
String S = "";
int input=0, input_next=0;
FileInputStream in = new FileInputStream(filename);
boolean done = false;
int last = in.read();
input=in.read();
while (input != -1)
{
input_next = in.read();
String newS = Integer.toBinaryString(input);
if (input_next == -1 && last!=0)
{
int newS_length = last - newS.length();
if (newS_length<8)
for(int i=0; i<newS_length; i++)
newS = "0" + newS;
}
else
{
int newS_length = newS.length();
if (newS_length<8)
for(int i=0; i<(8-newS_length); i++)
newS = "0" + newS;
}
S += newS;
input = input_next;
}
in.close();
return S;
}
/*public static void main(String args[]) throws IOException
{
String S1 = "110100010000100011001010011001110010";
coding C = new coding();
C.encode(S1, "string.txt");
String S2 = C.decode("string.txt");
System.out.println("S1: " + S1);
System.out.println("S2: " + S2);
}*/
}