求段php crc 校正碼的計算方式(PHP異或)

來源:互聯網
上載者:User
比如我有段字串"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

這樣就正常了。
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.