gpt4 book ai didi

java - 将按位运算Java代码转换为PHP

转载 作者:搜寻专家 更新时间:2023-10-31 22:03:09 24 4
gpt4 key购买 nike

您好,有一种用 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 输出:C0E8F098php 输出: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/

24 4 0
文章推荐: php - 使用 mediawiki 上传图片时出错(在 Directadmin 上)
文章推荐: css - 在 CSS 中将 margin-top 更改为 div
文章推荐: html - 根据行数动态地在
中垂直居中 ?