Home > Backend Development > PHP Tutorial > 求段php crc 校验码的计算方式(PHP异或)

求段php crc 校验码的计算方式(PHP异或)

WBOY
Release: 2016-06-23 13:48:04
Original
1194 people have browsed it


比如我有段字符串"139c",用计算器计算校验码, 把  13^9c=  复制到计算器用16进制计算得出 8F 是正确的

用PHP计算:

echo dechex(0x13^0x9c); //结果为 8f,正确echo "<hr>";$s1 = '0x13';$s2 = '0x9c';echo dechex($s1^$s2);//结果为 0, 错误echo "<hr>";$s3 = '13';$s4 = '9c';echo dechex($s3^$s4); //结果为 0 , 错误
Copy after login



把值赋到变量里计算结果跟直接写结果不一样,很纳闷。。。请各位指点一下,或给出个可用的计算函数


回复讨论(解决方案)

PHP的 与或运算 如果前后全是字符串 则通过asc码进行与或

$s1 = '0x13';
$s2 = '0x9c';

转化成asc 进行与或 则为
‘0’ ‘x’ ‘1’ ‘3’
00110000 01111000 00110001 00110011
^
00110000 01111000 00111001 01100011
----------------------------------------------------------------
00000000 00000000 00001000 01010000

结果是 var_dump(chr(0).chr(0).chr(8).chr(80)) 应该是 string(4)"P" 因为用3个非打印字符


dechex转换是按照从数字字符开始(ASC从48到57才识别 其他的都不识别)到尾部或者非数字字符
所以结果是0

$s1 = 0x13;$s2 = 0x9c;echo dechex($s1^$s2);
Copy after login
8f
没有问题

$s1 = '0x13';
$s2 = '0x9c';
是字符串 0x变成字符了

$s1 = 0x13;
$s2 = 0x9c;
这两个是16进制数,当然不同了。

$s1 = hexdec('0x13');$s2 = hexdec('0x9c');echo dechex($s1^$s2); // 8F$s3 = hexdec('13');$s4 = hexdec('9c');echo dechex($s3^$s4); // 8F
Copy after login

这样就正常了。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template