Created
September 13, 2011 14:27
-
-
Save asterite/1213926 to your computer and use it in GitHub Desktop.
My compression algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
class Compressor { | |
function compress($input, $output) { | |
$input = fopen($input, 'r'); | |
$output = fopen($output, 'w'); | |
while($line = fread($input, 8)) { | |
$lineLength = strlen($line); | |
for($i = 0; $i < $lineLength; $i += 8) { | |
$n = 0; | |
for($j = $i; $j < $i + 8; $j++) { | |
$n += $this->encode($line{$j}); | |
if ($j != $i + 7) { | |
$n = $n << 5; | |
} | |
} | |
for($j = 0; $j < 5; $j++) { | |
fwrite($output, pack('C', $n % 256)); | |
$n = (int)($n / 256); | |
} | |
} | |
} | |
fclose($input); | |
fclose($output); | |
} | |
function decompress($input, $output) { | |
$input = fopen($input, 'r'); | |
$output = fopen($output, 'w'); | |
$letters = array(); | |
while($line = fread($input, 1000)) { | |
$lineLength = strlen($line); | |
for($i = 0; $i < $lineLength; $i += 5) { | |
$n = 0; | |
for($j = $i + 4; $j >= $i; $j--) { | |
$n += ord($line{$j}); | |
if ($j != $i) { | |
$n = $n << 8; | |
} | |
} | |
for($j = 0; $j < 8; $j++) { | |
$letters[$j] = $this->decode($n % 32); | |
$n = (int)($n / 32); | |
} | |
for($x = 7; $x >= 0; $x--) { | |
fwrite($output, $letters[$x]); | |
} | |
} | |
} | |
fclose($input); | |
fclose($output); | |
} | |
private function encode($char) { | |
$char = ord($char); | |
switch($char) { | |
case 32: // space | |
return 26; | |
case 10: // enter | |
return 27; | |
case 44: // , | |
return 28; | |
case 46: // . | |
return 29; | |
default: | |
if (97 <= $char && $char <= 122) { | |
return $char - 97; | |
} else { | |
return $char - 65; | |
} | |
} | |
} | |
private function decode($num) { | |
switch($num) { | |
case 26: | |
return ' '; | |
case 27: | |
return "\n"; | |
case 28: | |
return ','; | |
case 29: | |
return '.'; | |
default: | |
return chr($num + 97); | |
} | |
} | |
} | |
$compressor = new Compressor(); | |
$compressor->compress('../php_nextive_data/compression_dummy_data.txt', '../php_nextive_data/output.txt'); | |
$compressor->decompress('../php_nextive_data/output.txt', '../php_nextive_data/output2.txt'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment