Algorithm-Hamming-Perl

 view release on metacpan or  search on metacpan

Perl.pm  view on Meta::CPAN


# unhamming - this is a wrapper around unhamming_err that just returns 
#		the data.
#
sub unhamming {
	my $data = shift;
	my ($output,$err);

	($output,$err) = unhamming_err($data);
	return $output;
}


# unhamchar - this takes a hamming code as binary text "0101..." and returns
#		both the char and number (0 or 1) to represent if correction
#		occured.
#
sub unhamchar {
	my $text = shift;
	my $pos = 0;				# counter
	my $err = 0;				# error bit position
	my ($bit);

	### If okay, return now
	if (defined $Hamming8rev{$text}) {
		return ($Hamming8rev{$text},0);
	}

	### Find error bit
	my $copy = $text;
	while ($copy ne "") {
		$pos++;
		$bit = chop($copy);
		if ($bit eq "1") {
			$err = $err ^ $pos;
		}
	}

	### Correct error bit
	$copy = $text;
	if ($err <= 12) {
		$bit = substr($copy,-$err,1);
		if ($bit eq "0") { $bit = "1"; }
		 else { $bit = "0"; }
		substr($copy,-$err,1) = $bit;
	}

        ### If okay now, return
        if (defined $Hamming8rev{$copy}) {
                return ($Hamming8rev{$copy},1);
        }

	### We shouldn't get here
	return ("\0",1);
}



1;
__END__
# Below is stub documentation for your module. You better edit it!

=head1 NAME

Algorithm::Hamming::Perl - Perl implementation of ECC Hamming encoding, 
for single bit auto error correction.

=head1 SYNOPSIS

use Algorithm::Hamming::Perl  qw(hamming unhamming);

$code = hamming($data);              # Encode $data

$data = unhamming($code);            # Decode and fix errors
($data,$errors) = unhamming($code);  #  + return error count


=head1 DESCRIPTION

This is an Error Correction Code module, implementing Hamming encoding
(8 bits data, 4 bits Hamming - ie increases data size by 50%). Data can
be encoded so that single bit errors within a byte are auto-corrected.

This may be useful as a precaution before storing or sending data where
single bit errors are expected.

Hamming encoding was invented by Richard Hamming, Bell Labs, during 1948.

=head1 EXPORT SUBROUTINES

=over 4

=item hamming (SCALAR)

Returns the Hamming code from the provided input data.

=item unhamming (SCALAR)

Returns the original data from the provided Hamming code. Single bit errors
are auto corrected.

=item unhamming_err (SCALAR)

Returns the original data from the provided Hamming code, and a number counting
the number of bytes that were corrected. Single bit errors are auto corrected. 

=back

=head1 OTHER SUBROUTINES

=over 4

=item Algorithm::Hamming::Perl::hamming_faster ()

This is an optional subroutine that will speed Hamming encoding if it is
run once at the start of the program. It does this by using a larger (hash)
cache of preprocessed results. The disadvantage is that it uses more memory,
and can add several seconds to invocation time. Only use this if you are
encoding more than 1 Mb of data.

=back



( run in 0.445 second using v1.01-cache-2.11-cpan-13bb782fe5a )