-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySystem.java
More file actions
89 lines (64 loc) · 2.08 KB
/
Copy pathBinarySystem.java
File metadata and controls
89 lines (64 loc) · 2.08 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package otp;
public class BinarySystem {
// (American Standard Code for Information Interchange) ASCII
public static String convertDecimalToBinary(String plainText) {
return stringtoBinary(plainText);
}
private static String reverse(String binary) {
String reversedBinary = "";
for (int i = binary.length() - 1; i >= 0; i--) {
reversedBinary += binary.charAt(i);
}
return reversedBinary;
}
private static String getBinary(char a) {
String binary = "";
int intgerValue = Integer.valueOf(a);
// System.out.println(intgerValue);
while (intgerValue > 0) {
if (intgerValue % 2 == 0) {
binary += "0";
} else {
binary += "1";
}
intgerValue = (int) intgerValue / 2;
}
if (binary.length() < 8) {
while (binary.length() < 8) {
binary += "0";
}
}
return reverse(binary);
}
private static String stringtoBinary(String text) {
String binaryFull = "";
for (int i = 0; i < text.length(); i++) {
binaryFull += getBinary(text.charAt(i));
}
return binaryFull;
}
public static int getASCIIForBinaryChar(String binaryChar) {
String binary = reverse(binaryChar);
int sum = 0;
for (int i = 0; i < binary.length(); i++) {
int a = Integer.parseInt(String.valueOf(binary.charAt(i)));
sum += Math.pow(2, i) * a;
}
return sum;
}
public static String convertBinaryToString(String binary) {
// get each 8
// reverse
// apply pow math
// get number value
String plainText = "";
for (int i = 0; i < binary.length()/8; i++) {
int start = i*8;
int end = (i*8)+8;
String charBinary = binary.substring(start,end);
int acsiiValue = getASCIIForBinaryChar(charBinary);
plainText += (char) acsiiValue;
}
return plainText;
}
}