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;
}
} < spanstyle = "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
字符串函数php
E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569
要加密的内容sxfenglei
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。