Skip to content

Instantly share code, notes, and snippets.

@llamadonica
Created December 4, 2012 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llamadonica/4199659 to your computer and use it in GitHub Desktop.
Save llamadonica/4199659 to your computer and use it in GitHub Desktop.
Galois Field Reciprocal in PERL
#!/usr/bin/perl
$modulo = 0x1f9;
$order = msb($modulo);
sub gf_add {
return $_[0] ^ $_[1];
}
sub msb {
if ($_[0] == 0) { return -1;}
my $i = 0; $_ = $_[0];
while ($_ != 1) {
$i++;
$_ = $_ >> 1;
}
return $i;
}
sub poly_div_mod {
my $current_number = $_[0]; my $modulo = $_[1];
my $current_order = msb($current_number);
my $order = msb($modulo);
my $quotient = 0;
while ($current_order >= $order) {
$quotient = $quotient ^ (1 << ($current_order - $order));
$current_number = $current_number ^ ($modulo << ($current_order - $order));
$current_order = msb($current_number );
}
return ($quotient,$current_number);
}
sub poly_multiply {
my $a = $_[0]; my $b = $_[1];
my $result;
while ($b > 0) {
if ($b & 1) {
$result = $result ^ $a;
}
$b = $b >> 1;
$a = $a << 1;
}
return $result;
}
sub gf_multiply {
my $q;
($_,$q) = poly_div_mod(poly_multiply($_[0],$_[1]),$modulo);
return $q;
}
sub gf_invert {
my $a = $modulo;
my $b = $_[0];
if ($b == 0) {return -1;}
my $aux_2 = 0;
my $aux_1 = 1;
my $aux_0;
my $remainder; my $quotient;
while ($b != 1) {
($quotient,$remainder) = poly_div_mod($a,$b);
$aux_0 = gf_multiply($aux_1,$quotient) ^ $aux_2;
$a = $b; $b = $remainder;
$aux_2 = $aux_1; $aux_1 = $aux_0;
}
return $aux_0;
}
for (my $i = 2; $i < 256; $i++) {
printf ("0x%02x\n", gf_multiply($i,gf_invert ($i)));
}
my @primes = (2,3);
outer_loop: for (my $i=4;$i<512;$i++) {
#Incidentally this is much faster than the HAskell version I did
inner_loop: foreach my $prime (@primes) {
my $q; my $r;
($q,$r) = poly_div_mod($i,$prime);
if ($r == 0) {next outer_loop;}
}
push @primes, $i;
printf ("0x%04x\n", $i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment