|
- <?php
- /*
- 2~256进制bin数据转换
- 如果需要对数字、大小写字母进行进制转换,则需要先对字符串进行以下编码:
- 0~9转换成chr(0)~chr(9),
- A~Z转换成chr(10)~chr(35)
- a~z转换成chr(36)~chr(61)
- 转换后解码即可,否则将无法正常转换,失败返回空。
- 参数1:转换的数据 (此函数可安全用于二进制对象)
- 参数2:原进制 (2进制为1、3进制为2、256进制为255)
- 参数3:目标进制
- */
- function bin_carry_convert($data,$old,$new){
- $old &= 255;
- $new &= 255;
- $k = 0;
-
- $return = array();
- $len = strlen($data);
- $data_array = array();
- if($old <=0 || $new <= 0 || $len <= 0){
- return;
- }elseif($old == $new) {
- return $data;
- }
- $old2 = $old+1;$new2 = $new+1;
-
- for($i=0;$i<$len;$i++){
- $data_array[$i] = ord($data[$i]);
- if($data_array[$i] > $old){
- return;
- }
- }
- while($len >= 1){
- $j = 0;
- for($i=0;$i<$len;$i++){
- $j = $j * $old2 + $data_array[$i];
- $data_array[$i] = floor($j / $new2);
- $j %= $new2;
- }
- $return[$k++] = chr($j);
- $j = 0;
- while($j < $len && $data_array[$j] == 0){
- $j++;
- }
- array_splice($data_array,0,$j);
- $len=sizeof($data_array);
- }
- return implode(array_reverse($return));
- }
- function carry_convert_encode($text){ //进制转换前对字符串进行编码
- $len = strlen($text)-1;
- if($len <= -1) return;
- do {
- $ascii = ord($text[$len]);
- if($ascii >= 48 && $ascii <= 57){
- $ascii -= 48;
- }elseif($ascii >= 65 && $ascii <= 90){
- $ascii -= 55;
- }elseif($ascii >= 97 && $ascii <= 122){
- $ascii -= 61;
- }
- $text[$len] = chr($ascii);
- } while($len--);
- return $text;
- }
- function carry_convert_decode($text){ //进制转换后对数据解码成字符串
- $len = strlen($text)-1;
- if($len <= -1) return;
- do {
- $ascii = ord($text[$len]);
- if($ascii >= 0 && $ascii <= 9){
- $ascii += 48;
- }elseif($ascii >= 10 && $ascii <= 35){
- $ascii += 55;
- }elseif($ascii >= 36 && $ascii <= 61){
- $ascii += 61;
- }
- $text[$len] = chr($ascii);
- } while($len--);
- return $text;
- }
- function text_carry_convert($text,$old,$new){ //文本2~62进制转换
- if($old == $new){
- return $text;
- } elseif($old < 2 || $new < 2 || $old > 62 || $new > 62){
- return;
- }
- return carry_convert_decode(bin_carry_convert(carry_convert_encode($text),$old-1,$new-1));
- }
- function base_encode($data,$base = 62){ //Base2~62编码程序(失败返回空文本)
- if($base < 2 || $base > 62) return;
- return carry_convert_decode(bin_carry_convert($data,255,$base-1));
- }
- function base_decode($text,$base = 62){ //Base2~62解码程序(失败返回空文本)
- if($base < 2 || $base > 62) return;
- return bin_carry_convert(carry_convert_encode($text),$base-1,255);
- }
- echo text_carry_convert("2147483647",10,16)."<br>";
- echo text_carry_convert("4294967295",10,16)."<br>";
- echo text_carry_convert("11111111111111111111111111111111",2,62)."<br>";
- echo text_carry_convert("10101010101010101010101010101010",2,62)."<br>";
- echo base_encode("Hello World!编码测试",62)."<br>";
- echo base_decode("AKRfxYADWZlc0yHqZ9T6Q8mou4C",62)."<br>";
- ?>
复制代码
|
|