- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
您好,有一种用 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
我应该查看这些代码中的哪些差异来解决它?
最佳答案
让我们让 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]);
关于java - 将按位运算Java代码转换为PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24116015/
我是一名优秀的程序员,十分优秀!