php版本长整形压缩为ascii

用途

有时需要将长整型缩短,以便把于传输或减少字符输入;

实现

基于进制原理,进行转码

代码

<?php
function packInt2Asc($l){
	$table = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST+=';
	$divisor = strlen($table);

	$sum = '';

	while($l >= $divisor){
		$remainder = intval($l % $divisor);
		$res = intval($l / $divisor);
		$sum = $table[$remainder] . $sum;
		$l = $res;
	}
	$remainder = intval($l % $divisor);
	$sum = $table[$remainder] . $sum;

	return $sum;
}

function unpackAsc2Int($s){
	$table = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST+=';
	$divisor = strlen($table);

	$res = 0;
	for($i = 0; $i<strlen($s); $i++){
		$pos = strpos($table, $s[$i]);
		if ($pos === false)
			throw Exception("not found {$s[$i]} in tables");
		$res = $res * $divisor + $pos;
	}
	return $res;
}

$test_number = 3340269857578;
echo "test number: {$test_number} \n";

$asc = packInt2Asc($test_number);
echo "after pack: {$asc} \n";

$res = unpackAsc2Int($asc);
echo "after unpack {$res} \n";

if ($test_number != $res)
	echo "fail! \n";
else
	echo "passed ! \n";
?>

结果

test number: 3340269857578 
after pack: fHfitFwk 
after unpack 3340269857578 
passed ! 

长度缩小一半.

发布了25 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jamsan_n/article/details/83151305