Added binary encoding

This commit is contained in:
2022-01-08 14:05:34 -05:00
parent b9ccfce5a2
commit f4d4585bc6
2 changed files with 178 additions and 0 deletions

View File

@@ -0,0 +1,96 @@
//CipherStreamJava/src/main/java/com/mattrixwv/CipherStreamJava/monoSubstitution/Binary.java
//Mattrixwv
// Created: 01-08-22
//Modified: 01-08-22
package com.mattrixwv.CipherStreamJava.monoSubstitution;
import java.util.StringJoiner;
import com.mattrixwv.CipherStreamJava.exceptions.InvalidCharacterException;
public class Binary{
private String inputString; //The string that needs encoded/decoded
private String outputString; //The encoded/decoded string
//Sets the input string
private void setInputStringEncode(String inputString){
this.inputString = inputString;
}
private void setInputStringDecode(String inputString) throws InvalidCharacterException{
this.inputString = inputString.replaceAll("[^01\\s]", "");
if(this.inputString != inputString){
throw new InvalidCharacterException("inputString cannot contain anything except 0's, 1's, and whitespace");
}
}
//Encode inputString, store it in outputString, and return it
private String encode(){
//Encode every character in inputString
StringJoiner output = new StringJoiner(" ");
for(int cnt = 0;cnt < inputString.length();++cnt){
//Get the next character
char ch = inputString.charAt(cnt);
//Encode the character to binary and add it to the output
output.add(Integer.toString(ch, 2));
}
//Save the output
outputString = output.toString();
//Return the output
return outputString;
}
//Decode inputString, store it in outputString, and return it
private String decode() throws InvalidCharacterException{
//Decode every binary number in the string
StringBuilder output = new StringBuilder();
for(String binary : inputString.split(" ")){
//Decode the current binary number
int num = Integer.valueOf(binary, 2);
//Make sure it is in a valid range
if((num < 0) && (num > 255)){
throw new InvalidCharacterException("The binary string '" + binary + "' is not a valid character");
}
//Convert the int to a char and save it
output.append((char)num);
}
//Save the output
outputString = output.toString();
//Return the output
return outputString;
}
//Constructor
public Binary(){
reset();
}
//Returns the inputString
public String getInputString(){
return inputString;
}
//Returns the outputString
public String getOutputString(){
return outputString;
}
//Sets the inputString and encodes the message
public String encode(String inputString){
reset();
setInputStringEncode(inputString);
return encode();
}
//Sets the inputString and decodes the message
public String decode(String inputString) throws InvalidCharacterException{
reset();
setInputStringDecode(inputString);
return decode();
}
//Makes sure all of the variables are empty
public void reset(){
inputString = "";
outputString = "";
}
}