mi vergogno di questo, ma è il meglio che ne potessi togliere fuori
codice:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Pagina senza titolo</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
var cod = "";
function Button1_onclick()
{
var a = document.getElementById("Text1").value;
var s = codifica(a);
cod = s;
document.getElementById("span1").innerHTML = s;
//for(var i = 0; i < s.length; i++) alert(s.charCodeAt(i));
}
function Button2_onclick()
{
var a = cod;
var s = decodifica(a);
document.getElementById("span2").innerHTML = s;
//for(var i = 0; i < s.length; i++) alert(s.charCodeAt(i));
}
function codifica(a)
{
var s = "";
var key = 0;
var keyp = 0;
var b3tmp = 0;
var b3 = 0;
for(var i = a.length - 1; i >= 0; i--)
{
key = a.charCodeAt(i); //ricavo il codice carattere
b3 = (key & 7);//recupero i tre bit meno significativi (quelli di destra)
key = (key >> 3); //sposto tutti i bit di tre posizioni verso destra
//memorizzo questi tre bit dell'ultimo carattere da usare per il primo carattere
if(i == a.length - 1)
{
b3tmp = b3;
}
else
{
//nel carattere precedente aggiungo i tre bit persi del carattere corrente
keyp = ((b3 << 5) | keyp);
//compongo la stringa
s = String.fromCharCode(keyp) + s;
}
keyp = key;
}
//aggiungo nel carattere corrente i tre bit memorizzati nel primo carattere considerato
key = keyp;
keyp = ((b3tmp << 5) | keyp);
s = String.fromCharCode(keyp) + s;
return s;
//for(var i = 0; i < s.length; i++) alert(s.charCodeAt(i));
}
function decodifica(a)
{
var s = "";
var key = 0;
var keyp = 0;
var b3tmp = 0;
var b3 = 0;
for(var i = 0; i < a.length; i++)
{
key = a.charCodeAt(i); //ricavo il codice carattere
b3 = (key & 224);//recupero i tre bit più significativi (quelli di sinistra)
key = ((key << 3) & 255); //sposto tutti i bit di tre posizioni verso sinistra (voglio solo otto bit)
//memorizzo questi tre bit dell'ultimo carattere da usare per il primo carattere
if(i == 0)
{
b3tmp = b3;
}
else
{
//nel carattere precedente aggiungo i tre bit persi del carattere corrente
keyp = ((b3 >> 5) | keyp);
//compongo la stringa
s = s + String.fromCharCode(keyp);
}
keyp = key;
}
//aggiungo nel carattere corrente i tre bit memorizzati nel primo carattere considerato
key = keyp;
keyp = ((b3tmp >> 5) | keyp);
s = s + String.fromCharCode(keyp);
return s;
//for(var i = 0; i < s.length; i++) alert(s.charCodeAt(i));
}
// ]]>
</script>
</head>
<body>
<h3>Scrivi qualcosa, poi premi codifica per codificare e decodifica per decodificare, in successione</codifica></h3>
<input id="Text1" type="text" value="ABCD" />
<input id="Button1" type="button" value="codifica" onclick="return Button1_onclick()" style="width: 86px" />
<span id="span1"></span>
<input id="Button2" type="button" value="decodifica" onclick="return Button2_onclick()" style="width: 86px" />
<span id="span2"></span>
</body>
</html>