Files

126 lines
3.4 KiB
JavaScript

/**
* Created by Giovanni on 15/05/2015.
*/
function dec_to_hex ( input ) {
var t = input.toString(16);
if (t.length == 1 )
return "0" + t;
return t;
}
function bin_to_hex ( input ) {
return dec_to_hex(parseInt(input,2));
}
function dec_to_bin ( input ) {
var t = input.toString(2);
var ret=t;
if (t.length < 8 )
for (var i = 0 ; i < (8 - t.length) ; i++){
ret = "0" + ret;
}
return ret;
}
function hex_to_bin (input) {
return dec_to_bin(parseInt(input, 16));
}
function hex_to_dec(input){
return parseInt(input, 16);
}
function bin_to_dec(input){
return parseInt(input, 2);
}
function matchExact(r, str) {
var match = str.match(r);
return match != null && str == match[0];
}
var byte = function (string){
if (string == undefined || string.length > 8 || !matchExact(/((?:[0-1]+)*)/,string))
this.content= ["0","0","0","0","0","0","0","0"];
else
{
this.content= [];
for (var i = 0; i < (8 - string.length); i++) {
this.content[i] = 0;
}
for (; i < 8; i++) {
this.content[i] = string[i - 8 + string.length];
}
}
this.hex = function (){return dec_to_hex(this.dec())};
this.bin=function (){
var t="";
for (var i = 0 ; i< 8 ; i++){
t = t + this.content[i];
}
return t;
};
this.dec =function(){return bin_to_dec(this.bin())};
this.set = function(string){
if (string == undefined || string.length > 8 || !matchExact(/((?:[0-1]+)*)/,string))
this.content= ["0","0","0","0","0","0","0","0"];
else
{
this.content= [];
for (var i = 0; i < (8 - string.length); i++) {
this.content[i] = 0;
}
for (; i < 8; i++) {
this.content[i] = string[i - 8 + string.length];
}
}
}
};
function xor_byte (first,second){
var ret = new byte();
for (var i = 0; i< 8; i++){
if ( (first.content[i] == "0" && second.content[i] == "0" ) || (first.content[i] == "1" && second.content[i] == "1" ))
ret.content[i] = "0";
else
ret.content[i] = "1";
}
return ret;
}
var word = function (b1,b2,b3,b4){
if (arguments.length !=4 ) {
this.byte0 = new byte();
this.byte1 = new byte();
this.byte2 = new byte();
this.byte3 = new byte();
} else {
this.byte0 = new byte(b1);
this.byte1 = new byte(b2);
this.byte2 = new byte(b3);
this.byte3 = new byte(b4);
}
this.bin = function(){
return this.byte0.bin() + this.byte1.bin() + this.byte2.bin() + this.byte3.bin();
}
this.hex = function(){
return this.byte0.hex() + this.byte1.hex() + this.byte2.hex() + this.byte3.hex();
}
};
function xor_word (first,second){
var byte0 = xor_byte(first.byte0,second.byte0);
var byte1 = xor_byte(first.byte1,second.byte1);
var byte2 = xor_byte(first.byte2,second.byte2);
var byte3 = xor_byte(first.byte3,second.byte3);
var ret = new word(byte0.bin(),byte1.bin(),byte2.bin(),byte3.bin());
return ret;
}
function input(hex){
var ret = [];
for (var i = 0 ; i< hex.length;i+=2){
ret.push(new byte(hex_to_bin(hex[i] + "" + hex[i+1])));
}
return ret;
}
function output (out){
var ret="";
for (var i=0;i <out.length;i++){
ret+=out[i].hex();
}
return ret;
}