Aer Interpreter Source
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

79 lines
2.8 KiB

class Base32 {
private static char[] $map = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', '2', '3', '4', '5', '6', '7',
'='
};
private static int[] $flippedMap = {
'A'=>0, 'B'=>1, 'C'=>2, 'D'=>3, 'E'=>4, 'F'=>5, 'G'=>6, 'H'=>7,
'I'=>8, 'J'=>9, 'K'=>10, 'L'=>11, 'M'=>12, 'N'=>13, 'O'=>14, 'P'=>15,
'Q'=>16, 'R'=>17, 'S'=>18, 'T'=>19, 'U'=>20, 'V'=>21, 'W'=>22, 'X'=>23,
'Y'=>24, 'Z'=>25, '2'=>26, '3'=>27, '4'=>28, '5'=>29, '6'=>30, '7'=>31
};
public static string encode(string $input, bool $padding = true) {
if(!$input) return '';
char[] $aInput = str_split($input);
string $binaryString = '';
for(int $i = 0; $i < sizeof($aInput); $i++) {
$binaryString += str_pad(base_convert(ord($aInput[$i]), 10, 2), 8, '0', STR_PAD_LEFT);
}
string[] $fiveBitBinaryArray = str_split($binaryString, 5);
string $base32 = '';
$i = 0;
while($i < sizeof($fiveBitBinaryArray)) {
$base32 += Base32::$map[base_convert(str_pad($fiveBitBinaryArray[$i], 5,'0'), 2, 10)];
$i++;
}
int $x;
if($padding && ($x = strlen($binaryString) % 40) != 0) {
if($x == 8) $base32 += str_repeat(Base32::$map[32], 6);
else if($x == 16) $base32 += str_repeat(Base32::$map[32], 4);
else if($x == 24) $base32 += str_repeat(Base32::$map[32], 3);
else if($x == 32) $base32 += Base32::$map[32];
}
return $base32;
}
public static string decode(string $input) {
if(!$input) return '';
int $paddingCharCount = substr_count($input, Base32::$map[32]);
int[] $allowedValues = {6, 4, 3, 1, 0};
if(!in_array($paddingCharCount, $allowedValues)) return '';
for(int $i = 0; $i < 4; $i++) {
if($paddingCharCount == $allowedValues[$i] && substr($input, -($allowedValues[$i])) != str_repeat(Base32::$map[32], $allowedValues[$i]))
return '';
}
$input = str_replace('=','', $input);
char[] $aInput = str_split($input);
string $binaryString = '';
for($i = 0; $i < sizeof($aInput); $i = $i + 8) {
string $x = '';
if(!in_array($input[$i], Base32::$map))
return '';
for(int $j = 0; $j < 8; $j++) {
if($i + $j < strlen($input)) {
if(array_key_exists($input[$i + $j], Base32::$flippedMap)) {
$x += str_pad(base_convert(Base32::$flippedMap[$input[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
}
}
}
string[] $eightBits = str_split($x, 8);
for(int $z = 0; $z < sizeof($eightBits); $z++) {
char $y;
$binaryString += (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
}
}
return $binaryString;
}
}
class Program {
public void main() {
var_dump(Base32::encode('Test String'), Base32::encode('DS27DEC985'), Base32::encode('AerScript rocks!'));
var_dump(Base32::decode('KRSXG5BAKN2HE2LOM4======'), Base32::decode('IRJTEN2EIVBTSOBV'), Base32::decode('IFSXEU3DOJUXA5BAOJXWG23TEE======'));
}
}