比如我有段字串"139c",用計算機計算校正碼, 把 13^9c= 複製到計算機用16進位計算得出 8F 是正確的
用PHP計算:
echo dechex(0x13^0x9c); //結果為 8f,正確echo "";$s1 = '0x13';$s2 = '0x9c';echo dechex($s1^$s2);//結果為 0, 錯誤echo "";$s3 = '13';$s4 = '9c';echo dechex($s3^$s4); //結果為 0 , 錯誤
把值賦到變數裡計算結果跟直接寫結果不一樣,很納悶。。。請各位指點一下,或給出個可用的計算函數
回複討論(解決方案)
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);
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
這樣就正常了。