forked from kalmar/DALGLI0
03 encode
This commit is contained in:
parent
be73ad2fde
commit
140e6a4606
13
03-rozwiazanie.js
Normal file
13
03-rozwiazanie.js
Normal file
@ -0,0 +1,13 @@
|
||||
const crc = require("./crc.js");
|
||||
let message = process.argv[3];
|
||||
let flag = process.argv[2];
|
||||
switch (flag) {
|
||||
case '-e':
|
||||
console.log(crc.encode(message));
|
||||
break;
|
||||
case '-d':
|
||||
|
||||
break;
|
||||
default:
|
||||
throw "incorect flag"
|
||||
}
|
64
crc.js
Normal file
64
crc.js
Normal file
@ -0,0 +1,64 @@
|
||||
let Polynomial = require('./polynomial.js');
|
||||
|
||||
const to_bytes_ascii = a => a.charCodeAt(0);
|
||||
const from_bytes_ascii = a => String.fromCharCode(a);
|
||||
const to_bin = a => {
|
||||
var result = "";
|
||||
for (var i = 0; i < a.length; i++) {
|
||||
var bin = a[i].charCodeAt().toString(2);
|
||||
result += Array(8 - bin.length + 1).join("0") + bin;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
const to_ascii = a => {
|
||||
a = a.join('');
|
||||
return String.fromCharCode(parseInt(a, 2));;
|
||||
}
|
||||
|
||||
|
||||
|
||||
const fcs = m => {
|
||||
bits = m.map(to_bin); //message in binary
|
||||
bits = bits.join('').split('').reverse(); //reverse binary decoded message
|
||||
let M = new Polynomial.Class(2, bits);
|
||||
let L = new Polynomial.Class(2, new Array(16).fill(1));
|
||||
let X = new Polynomial.Class(2, [0, 1]);
|
||||
let X16 = Polynomial.power(X, 16);
|
||||
let G = new Polynomial.Class(2, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]); //jako ze można to od razu wymnożyć
|
||||
|
||||
let fcs = Polynomial.multiply(X16, M);
|
||||
fcs = Polynomial.add(fcs,
|
||||
Polynomial.multiply(
|
||||
Polynomial.power(X, m.length * 8),
|
||||
L
|
||||
)
|
||||
)
|
||||
fcs = Polynomial.divide(fcs, G);
|
||||
for (let i = 0; i < 16 - fcs.coefficients.length; i++) fcs.coefficients.push(0);
|
||||
fcs.coefficients.reverse();
|
||||
return fcs.coefficients;
|
||||
}
|
||||
|
||||
|
||||
function encode(m) {
|
||||
m = m.split('');
|
||||
let res = fcs(m);
|
||||
|
||||
let f1 = [];
|
||||
let f2 = [];
|
||||
for (let i = 0; i < res.length; i++) {
|
||||
if (i < 8) {
|
||||
f1.push(res[i]);
|
||||
} else {
|
||||
f2.push(res[i]);
|
||||
}
|
||||
}
|
||||
f1 = to_ascii(f1);
|
||||
f2 = to_ascii(f2);
|
||||
m.push(f1);
|
||||
m.push(f2);
|
||||
return m;
|
||||
|
||||
}
|
||||
|
||||
exports.encode = encode;
|
@ -2,7 +2,14 @@ class Polynomial {
|
||||
constructor(mod, coefArray) {
|
||||
this.mod = mod;
|
||||
this.degree = (coefArray.length - 1);
|
||||
this.coefficients = coefArray;
|
||||
|
||||
this.coefficients = Array.from(coefArray); //zeby nie przekazywać referencji
|
||||
this.normalize();
|
||||
}
|
||||
normalize() {
|
||||
while (this.coefficients && this.coefficients[this.coefficients.length - 1] == 0) {
|
||||
this.coefficients.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user