例,php bcd碼壓縮-把十進位數字壓縮到十六進位資料中
| 代碼如下 |
複製代碼 |
<?php /* php bcd碼壓縮-把十進位數字壓縮到十六進位資料中 例如 0091 壓縮後 0x00 0x91 */ $string = '0091'; $bytes = Bytes::getBytes($string); print_r($bytes); /* Array ( [0] => 48 [1] => 48 [2] => 57 [3] => 49 ) */ $asc=Bytes::AscToHex($bytes,4); //4位壓縮成2位 print_r($asc); /* Array ( [0] => 0 [1] => 145 ) */ echo Bytes::toStr($asc); /* 0091 */ $hex=Bytes::HexToAsc($asc,2); //反操作2位還原成4位 print_r($hex); /* Array ( [0] => 48 [1] => 48 [2] => 57 [3] => 49 ) */ ?> |
例,把十進位數字壓縮到十六進位資料中
| 代碼如下 |
複製代碼 |
<?php /** * php bcd碼壓縮 * 把十進位數字壓縮到十六進位資料中 * @author phpff.com * Created on 2011-7-15 */ class Bytes { /** * 轉換一個String字串為byte數組 * @param $str 需要轉換的字串 * @param $bytes 目標byte數組 * @author phpff.com */ public static function getBytes($string) { $bytes = array(); for($i = 0; $i < strlen($string); $i++){ $bytes[] = ord($string[$i]); } return $bytes; } /** * 將位元組數組轉化為String類型的資料 * @param $bytes 位元組數組 * @param $str 目標字串 * @return 一個String類型的資料 */ public static function toStr($bytes) { $str = ''; foreach($bytes as $ch) { $str .= bin2hex(chr($ch)); } return $str; } /** * asc碼轉成16進位資料 * @param $asc asc數字字串 * @param $AscLen 需要轉換的字串長度 * @return 16進位數組 * @author phpff.com */ public static function AscToHex( $asc, $AscLen) { $i=0; $Hex=array(); for($i = 0; 2*$i < $AscLen; $i++) { /*A:0x41(0100 0001),a:0x61(0110 0001),右移4位後都是0001,加0x90等0xa*/ $Hex[$i] = (chr($asc[2*$i]) << 4); if (!(chr($asc[2*$i]) >= '0' && chr($asc[2*$i]) <= '9' )){ $Hex[$i] += 0x90; } if(2*$i+1 >= $AscLen){ break; } $Hex[$i] |= (chr($asc[2*$i+1]) & 0x0f); if (!(chr($asc[2*$i+1]) >= '0' && chr($asc[2*$i+1]) <= '9' )){ $Hex[$i] += 0x09; } } return $Hex; } /** * 將16進位的資料轉換成asc碼 * @param $Hex 16進位數組 * @param $HexLen 16進位數組長度 * @return asc數組 * @author phpff.com */ public static function HexToAsc($Hex, $HexLen) { $i=0; $Temp=0; for($i = 0; $i < $HexLen; $i++ ) { $Temp = ($Hex[$i] & 0xf0) >> 4; if ($Temp < 10){ $Asc[2*$i] = (0x30 + $Temp); }else{ $Asc[2*$i] = (0x37 + $Temp); } $Temp = $Hex[$i] & 0x0f; if ($Temp < 10){ $Asc[2*$i+1] = (0x30 + $Temp); }else{ $Asc[2*$i+1] = (0x37 + $Temp); } } return $Asc; } } ?> |