Let’s take a look at the article about PHP bcd code compression - compressing decimal numbers into hexadecimal data. I hope the article will be helpful to all students.
Example, php bcd code compression - compress decimal numbers into hexadecimal data
代码如下 |
复制代码 |
/*
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
)
*/
?> |
Example, compress decimal numbers into hexadecimal data
代码如下 |
复制代码 |
/**
*php bcd code compression
* Compress decimal numbers into hexadecimal data
* @author phpff.com
* Created on 2011-7-15
*/
class Bytes {
/**
* Convert a String to a byte array
* @param $str The string to be converted
* @param $bytes target byte array
* @author phpff.com
*/
public static function getBytes($string) {
$bytes = array();
for($i = 0; $i < strlen($string); $i++){
$bytes[] = ord($string[$i]);
}
return $bytes;
}
/**
* Convert byte array to String type data
* @param $bytes byte array
* @param $str target string
* @return a String type data
*/
public static function toStr($bytes) {
$str = '';
foreach($bytes as $ch) {
$str .= bin2hex(chr($ch));
}
return $str;
}
/**
* Convert asc code to hexadecimal data
* @param $asc asc numeric string
* @param $AscLen The length of the string to be converted
* @return hexadecimal array
* @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;
}
}
?>
|
http://www.bkjia.com/PHPjc/633105.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/633105.htmlTechArticle下面我们一起来看和篇关于php bcd码压缩-把十进制数字压缩到十六进制数据中实例,希望文章给各位同学带来帮助哦。 例,php bcd码压缩-把十...