当前位置:Gxlcms > PHP教程 > php 字符串转为16进制的方法

php 字符串转为16进制的方法

时间:2021-07-01 10:21:17 帮助过:35人阅读

php字符串转为16进制的方法:首先找到并打开common.php;然后添加strToHex函数;最后通过strToHex函数实现字符串转十六进制即可。

推荐:《PHP视频教程》

PHP 字符串和十六进制互转

今天在做项目中,因为要调用别人网站的接口,结果需要对请求和返回的时间进行十六进制加密处理,于是在网上查了下资料谢了一个转换Demo做个记录。

如果在TP下使用可以将下面函数放到common.php中

一,加密函数

<?php
/**
*字符串转十六进制函数
*@pream string $str='abc';
*/
function strToHex($str){
$hex="";
for($i=0;$i<strlen($str);$i++)
$hex.=dechex(ord($str[$i]));
$hex=strtoupper($hex);
return $hex;
}
?>

二、解密函数

<?php
/**
*十六进制转字符串函数
*@pream string $hex='616263';
*/
function hexToStr($hex){
$str="";
for($i=0;$i<strlen($hex)-1;$i+=2)
$str.=chr(hexdec($hex[$i].$hex[$i+1]));
return $str;
}
?>

加密 解密 转换 函数使用Demo事例,这里为了方便写在了一个类中。

<?php
class Test{
/**
*字符串转十六进制函数
*@pream string $str='abc';
*/
public function strToHex($str){
$hex="";
for($i=0;$i<strlen($str);$i++)
$hex.=dechex(ord($str[$i]));
$hex=strtoupper($hex);
return $hex;
}
/**
*十六进制转字符串函数
*@pream string $hex='616263';
*/
public function hexToStr($hex){
$str="";
for($i=0;$i<strlen($hex)-1;$i+=2)
$str.=chr(hexdec($hex[$i].$hex[$i+1]));
return $str;
}
}
<span style="white-space:pre"> </span>//测试Demo效果
$test = new Test();
$str = '要加密的内容sxfenglei';
$data = $test->strToHex($str);
echo '加密内容:要加密的内容sxfenglei <br>'.$data.'<hr>';
$output = $test->hexToStr($data);
echo '解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 <br>'.$output;
?>

运行结果:

加密内容:要加密的内容sxfenglei
E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
要加密的内容sxfenglei

以上就是php 字符串转为16进制的方法的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行