嗨,有一种计算用Java编写的校验和的方法。这是代码:
01 public String getChecksum() {
02 String checkSumBuffer = getMessageHeader() + getConversationHeader() + getTransactionHeader() + operationInformation;
03 char[] res = new char[4];
04 for (int j = 0; j < res.length; j++) {
05 for (int i = j; i < checkSumBuffer.length(); i = i + 4) {
06 res[j] = (char) (res[j] ^ checkSumBuffer.charAt(i));
07 }
08 res[j] = (char) ((~res[j]) & 0x00ff);
09 }
10 String strCheckSum = "";
11 for (int i = 0; i < 4; i++) {
12 strCheckSum = strCheckSum + Integer.toHexString((int) res[i]);
13 }
14 checksum = strCheckSum.toUpperCase();
15 return checksum;
16 }
这是PHP等效代码:
00 public function getChecksum() {
01 $checkSumBuffer = $this->getMessageHeader() . $this->getConversationHeader() . $this->getTransactionHeader() . $this->operationInformation;
02 $res = array(0,0,0,0); // array with 4 elements
03 for ($j = 0; $j < count($res); $j++) {
04 for ($i = $j; $i < strlen($checkSumBuffer); $i = $i + 4) {
05 $res[$j] = $res[$j] ^ $checkSumBuffer[$i];
06 }
07 $res[$j] = ((~$res[$j]) & 0x00ff);
08 }
09 $strCheckSum = "";
10 for ($i = 0; $i < 4; $i++) {
11 $strCheckSum = $strCheckSum . dechex($res[$i]);
12 }
13 $this->checksum = strtoupper($strCheckSum);*/
14 return $this->checksum;
15 }
但是PHP代码存在问题。这是每种方法的输出:
java输出:C0E8F098
php输出:FEFEFFFF
我认为问题是java代码中的res
变量是char类型,而在php代码中它是int
类型。如果这是问题,我该如何实现?我以为我可以使用chr
函数来获取ASCII
代码并返回该字符。但它不起作用,输出为:0000
我应该在这些代码中看到哪些差异来解决它?
答案 0 :(得分:0)
让php也使用char:
$res = array("\0", "\0", "\0", "\0"); // instead of $res = array(0,0,0,0);
$res[$j] = ((~$res[$j]) & "\xff"); // instead of $res[$j] = ((~$res[$j]) & 0x00ff);
$strCheckSum = $strCheckSum . bin2hex($res[$i]); // instead of $strCheckSum = $strCheckSum . dechex($res[$i]);