Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package telekom1;
- import java.util.Arrays;
- import java.util.Scanner;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.nio.file.Files;
- import java.nio.file.Paths;
- import java.nio.file.StandardOpenOption;
- public class Zadanie1 extends JFrame {
- private static final long serialVersionUID = -8665668833005883229L;
- private JButton dekodowanie, kodowanie;
- private JTextArea textDekoduj;
- private JTextArea textKoduj;
- private File encoded, decoded;
- // macierz korekcyjna
- private static final byte[][] H = {
- {1,1,1,0,0,1,1,1,1,0,0,0,0,0,0,0},
- {0,1,1,1,1,0,1,1,0,1,0,0,0,0,0,0},
- {1,0,0,1,0,1,0,1,0,0,1,0,0,0,0,0},
- {1,1,1,0,1,0,0,1,0,0,0,1,0,0,0,0},
- {0,1,0,1,0,1,1,0,0,0,0,0,1,0,0,0},
- {1,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0},
- {1,1,0,0,1,1,0,0,0,0,0,0,0,0,1,0},
- {1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1}};
- private byte[] T; // 16 bitów, 8 znak + 8 bity parzystości
- private byte[] control; // 8 bitów wynik mnozenia macierzy
- // mnożenie macierzy (T*H), wynik w control
- private void multiplyMatrix() {
- for (int i = 0; i < H.length; i++) {
- for (int j = 0; j < T.length; j++)
- control[i] += T[j] * H[i][j];
- control[i] %= 2;
- }
- }
- // zamienia znak ASCII na 8 bitw zapisanzch w Stringu
- public String ASCII2bin(byte c) {
- String tmp = Integer.toBinaryString(c);
- if (tmp.length() > 8)
- tmp = tmp.substring(tmp.length() - 8, tmp.length());
- while (tmp.length() < 8) {
- tmp = "0" + tmp;
- }
- return tmp;
- }
- // zamienia 8 bitw zapisanzch w Stringu na znak ASCII
- public byte bin2ASCII(String bin) {
- return (byte) Integer.parseUnsignedInt(bin, 2);
- }
- // ładuje String do tablicy T
- private void loadT(String bin) {
- byte[] b = bin.getBytes();
- for (int i = 0; i < b.length; i++) {
- b[i] -= 48; // 48 = ASCII '0'
- T[i] = b[i];
- }
- }
- // zamienia znak ASCII na jego reprezentacje 16 bitową
- private void encodeChar(char c) {
- loadT(ASCII2bin((byte) c));
- multiplyMatrix();
- // dopisz control do T
- for (int i = 8; i < T.length; i++)
- T[i] = control[i - 8];
- }
- // oblicza wektor błędu dla 16 bitów
- private void decodeChar(String bin) {
- loadT(bin);
- multiplyMatrix();
- }
- // sprawdza czy wystąpił błąd
- private boolean isCorrect() {
- for (int i = 0; i < control.length; i++) {
- if (control[i] == 1)
- return false;
- }
- return true;
- }
- // szuka 1 błędu, zwraca -1 gdy jest ich więcej
- private int findError() {
- boolean isFound;
- for (int i = 0; i < T.length; i++) {
- isFound = true;
- for (int j = 0; j < control.length; j++)
- if (H[j][i] != control[j]) {
- isFound = false;
- break;
- }
- if (isFound)
- return i;
- }
- return -1;
- }
- // szuka 2 błędy, zwraca -1 w indexes[0] gdy jest ich więcej
- private int[] findErrors() {
- boolean isFound;
- int[] indexes = new int[2]; // zawiera pozycje 2 błędów
- // podobnie jak wyżej, ale do tego sprawdza każdy z każdym
- for (int i = 0; i < T.length - 1; i++) {
- for (int j = i + 1; j < T.length; j++) {
- isFound = true;
- for (int k = 0; k < control.length; k++) {
- if (((H[k][i] + H[k][j]) % 2) != control[k]) {
- isFound = false;
- break;
- }
- }
- if (isFound) {
- indexes[0] = i;
- indexes[1] = j;
- return indexes;
- }
- }
- }
- indexes[0] = -1;
- indexes[1] = -1;
- return indexes;
- }
- // naprawia 1 błąd, gdy jest ich więcej przekierowuje dalej
- private boolean repairError() {
- int index = findError();
- if (index == -1) {
- return repairErrors();
- }
- // zmienia 0 -> 1 lub 1 -> 0
- T[index] += 1;
- T[index] %= 2;
- return true;
- }
- // naprawia 2 błędy, gdy jest ich więcej zwraca false
- private boolean repairErrors() {
- int[] indexes = findErrors();
- if (indexes[0] == -1 && indexes[1] == -1) {
- return false;
- }
- T[indexes[0]] += 1;
- T[indexes[0]] %= 2;
- T[indexes[1]] += 1;
- T[indexes[1]] %= 2;
- return true;
- }
- // koduje plik ze znakami ASCII na ich 16 bitową reprezentacje
- public String encodeString(String input) {
- String output = "";
- // usuń zbędne nowe linie
- input = input.replaceAll(" ", "");
- input = input.replaceAll("\n", "");
- // podziel String na pojedyncze znaki
- char[] chars = input.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- // zamienia znak i ładuje do T
- encodeChar(chars[i]);
- for (int j = 0; j < T.length; j++) {
- if (j == 8)
- output += " ";
- // zapisz 16 bitów do pliku
- output += T[j];
- }
- output += " \n";
- }
- // wyczyszczenie tablic
- Arrays.fill(control, (byte) 0);
- Arrays.fill(T, (byte) 0);
- return output;
- }
- // dekoduje plik z 16 bitową reprezentacją ASCII, wykrywając max 2 błędy
- public String decodeString(String input) throws Exception {
- String output = "";
- // usuń zbędne spacje i nowe linie
- input = input.replaceAll(" ", "");
- input = input.replaceAll("\n", "");
- String[] bins = new String[input.length() / 16];
- // podziel całość na 16 znakowe Stringi
- for (int i = 0, j = 0; i < input.length(); i += 16, j++) {
- bins[j] = input.substring(i, i + 16);
- if (bins[j].charAt(0) == '1') {
- bins[j] = "0" + input.substring(i + 1, i + 16);
- }
- }
- for (int i = 0; i < bins.length; i++) {
- // ładuje 16 bitów do T i liczy wektor błędu
- decodeChar(bins[i]);
- // wykryto błąd- natępuje próba jego naprawienia
- if (!isCorrect())
- if (!repairError())
- throw new Exception();
- String ascii = "";
- // złączenie 8 bitów znaku i zamiana na char
- for (int j = 0; j < 8; j++) {
- ascii += T[j];
- }
- output += (char) bin2ASCII(ascii);
- // wyczyszczenie tablicy control
- Arrays.fill(control, (byte) 0);
- }
- // wyczyszczenie tablicy T
- Arrays.fill(T, (byte) 0);
- return output;
- }
- void saveEncoded() throws IOException {
- String output = textKoduj.getText();
- output = output.replaceAll(" ", "");
- output = output.replaceAll("\n", "");
- String[] stringBytes = new String[output.length() / 8];
- // podziel całość na 8 znakowe Stringi
- for (int i = 0, j = 0; i < output.length(); i += 8, j++) {
- stringBytes[j] = output.substring(i, i + 8);
- }
- byte[] bytes = new byte[stringBytes.length];
- for (int i = 0; i < bytes.length; i++) {
- bytes[i] = bin2ASCII(stringBytes[i]);
- }
- Files.write(Paths.get(encoded.toURI()), bytes, StandardOpenOption.WRITE);
- }
- void saveDecoded() throws FileNotFoundException {
- PrintWriter out = new PrintWriter(decoded);
- out.write(textDekoduj.getText());
- out.close();
- }
- void encode() throws FileNotFoundException {
- //saveDecoded();
- String input = textDekoduj.getText();
- String outpt = encodeString(input);
- textKoduj.setText(outpt);
- }
- void decode() throws Exception {
- saveEncoded();
- String input = textKoduj.getText();
- String output = decodeString(input);
- textDekoduj.setText(output);
- }
- void reloadEncoded() throws IOException {
- byte[] bytes;
- bytes = Files.readAllBytes(Paths.get(encoded.toURI()));
- String input = "";
- for (int i = 0; i < bytes.length; i++) {
- input += ASCII2bin(bytes[i]);
- }
- textKoduj.setText(input);
- }
- void reloadDecoded() throws FileNotFoundException {
- Scanner in = new Scanner(decoded);
- // wczytaj wszystkie znaki
- String input = "";
- while (in.hasNextLine()) {
- input += in.nextLine();
- }
- textDekoduj.setText(input);
- in.close();
- }
- public Zadanie1(String name) throws FileNotFoundException, IOException {
- super(name);
- dekodowanie = new JButton("DEKODOWANIE");
- kodowanie = new JButton("KODOWANIE");
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setSize(500, 200);
- setLocation(50, 50);
- setLayout(new FlowLayout());
- add(kodowanie);
- add(dekodowanie);
- // inicjalizacja tablic
- T = new byte[16];
- control = new byte[8];
- //reloadEncoded();
- //reloadDecoded();
- kodowanie.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- File currentDirFile = new File(".");
- String helper = currentDirFile.getAbsolutePath();
- String currentDir;
- try {
- currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());
- encoded = new File(currentDir + "/kodowanie.txt");
- try {
- // jeśli pliki nie istnieją- utwórz je
- if (!encoded.exists())
- encoded.createNewFile();
- encode();
- saveEncoded();
- } catch (IOException e2) {
- e2.printStackTrace();
- }
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- });
- dekodowanie.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- File currentDirFile = new File(".");
- String helper = currentDirFile.getAbsolutePath();
- String currentDir;
- try {
- currentDir = helper.substring(0, helper.length() - currentDirFile.getCanonicalPath().length());
- decoded = new File(currentDir + "/dekodowanie.txt");
- try {
- // jeśli pliki nie istnieją- utwórz je
- if (!decoded.exists())
- decoded.createNewFile();
- // decode()
- decode();
- saveDecoded();
- ///////
- } catch (IOException e3) {
- e3.printStackTrace();
- }
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- }
- });
- textDekoduj = new JTextArea();
- textDekoduj.setBounds(1, 1, 1, 1);
- add(textDekoduj);
- textDekoduj.setColumns(10);
- textKoduj = new JTextArea();
- textKoduj.setBounds(1, 1, 1, 1);
- add(textKoduj);
- textKoduj.setColumns(10);
- setVisible(true);
- }
- public static void main(String[] args) throws FileNotFoundException, IOException {
- @SuppressWarnings("unused")
- Zadanie1 z1 = new Zadanie1("Telekomunikacja - zadanie 1");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement