I am trying to create a Hamming encoder/decoder using PHP and I've been trying to wrap my head around calculating the parity bits.
So far, in my script you can input a number, have that number encoded in 8421 code (BCD) or Gray code and have the encoded number show up on screen. I have also resorted to hard-coding the Gray and BCD code sequences.
The maximum size of the number you can input is 32 bit (4 billion), so if you input a number of that size you will need 40 data bits in your Hamming code.
The basic idea of what I want is: a user inputs a number, that number gets converted into Gray Code/8421 and then into Hamming code. Afterwards the user has the option to decode the number.
The issue that I'm having is that I cannot seem to figure out an algorithm that will dynamically generate parity bits and calculate them as needed. I have included the relevant code below.
Thank you!
encode.php
session_start();
if ( !isset($_POST['num_to_convert']) || !is_numeric($_POST['num_to_convert']) ){
$_SESSION['redirect']=1;
header ('Location: form.php');
}
else
{
$method=$_POST['metoda'];
$number=$_POST['num_to_convert'];
$string="$_POST[num_to_convert]";
$to_convert=str_split($string);
$encoded_value='';
// Pentru metoda 8421
if($method=='8421')
{
foreach($to_convert as $value)
{
switch($value){
case 0:
$encoded_value.="0000";
break;
case 1:
$encoded_value.="0001";
break;
case 2:
$encoded_value.="0010";
break;
case 3:
$encoded_value.="0011";
break;
case 4:
$encoded_value.="0100";
break;
case 5:
$encoded_value.="0101";
break;
case 6:
$encoded_value.="0110";
break;
case 7:
$encoded_value.="0111";
break;
case 8:
$encoded_value.="1000";
break;
case 9:
$encoded_value.="1001";
break;
}
}
}
// Pentru metoda Gray
if($method=='Gray')
{
foreach($to_convert as $value)
{
switch($value){
case 0:
$encoded_value.="0000";
break;
case 1:
$encoded_value.="0001";
break;
case 2:
$encoded_value.="0010";
break;
case 3:
$encoded_value.="0011";
break;
case 4:
$encoded_value.="0110";
break;
case 5:
$encoded_value.="0111";
break;
case 6:
$encoded_value.="0101";
break;
case 7:
$encoded_value.="0100";
break;
case 8:
$encoded_value.="1100";
break;
case 9:
$encoded_value.="1101";
break;
}
}
}
$_SESSION['num_to_convert']=$_POST['num_to_convert'];
$_SESSION['encoded_value']=$encoded_value;
$_SESSION['method']=$method;
header('Location: form.php');
}
form.php is just the input and output script, nothing to be seen there.