将按位操作Java代码转换为PHP
您好,有一种计算校验和的方法,它是用Java编写的。代码如下:将按位操作Java代码转换为PHP,java,php,bit-manipulation,bitwise-operators,Java,Php,Bit Manipulation,Bitwise Operators,您好,有一种计算校验和的方法,它是用Java编写的。代码如下: 01 public String getChecksum() { 02 String checkSumBuffer = getMessageHeader() + getConversationHeader() + getTransactionHeader() + operationInformation; 03 char[] res = new char[4]; 04 for (int j = 0;
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输出:feffff
我认为问题在于java代码中的res变量是char类型的,而php代码中的res变量是int类型的。如果这是问题所在,我如何实现这一点?我想我可以使用一个函数,它接受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]);
谢谢你,马瑞克。你救了我的命。给你很多吻:。非常感谢。