繁体   English   中英

将公式从 Java 移植到 PHP 时出现问题

[英]Problems porting formula from Java to PHP

I've been tasked with porting a small internal company formula/algorithm from Java to PHP, and have for the most part been successful, but am clearly going wrong somewhere because I'm not getting the same output from my ported version than I am来自 PHP 版本。 我对 PHP 比较陌生,对 Java 一无所知,所以我猜我在这两种语言的数学运算方式上遗漏了一个微妙但至关重要的区别,特别是在与doublefloor() ZC1C4252768E68A .

这里是原始的Java代码,需要用户以F999格式输入,生成一个四位数的output:

String input;

String Generate() {
    int charAt = (((this.input.charAt(0) * 5) * 2) - 698) + this.input.charAt(1);
    int charAt2 = ((((this.input.charAt(2) * 5) * 2) + charAt) + this.input.charAt(3)) - 528;
    charAt2 = ((charAt2 << 3) - charAt2) % 100;
    String valueOf = String.valueOf((((((259 % charAt) % 100) * 5) * 5) * 4) + ((((charAt2 % 10) * 5) * 2) + ((int) Math.floor((double) (charAt2 / 10)))));
    return valueOf.length() == 3 ? "0" + valueOf : valueOf.length() == 2 ? "00" + valueOf : valueOf.length() == 1 ? "000" + valueOf : valueOf;
}

这是我移植的 PHP 版本,当前使用字符串模拟用户输入:

$input = "F999"; # should output 2360

$charAt = ((((int) $input[0] * 5) * 2) - 698) + $input[1];
$charAt2 = (((($input[2] * 5) * 2) + $charAt) + $input[3]) - 528;
$charAt2 = (($charAt2 << 3) - $charAt2) % 100;
$valueOf = strval(((((((259 % $charAt) % 100) * 5) * 5) * 4) + (((($charAt2 % 10) * 5) * 2) + ((int) floor((double) ($charAt2 / 10))))));
if (strlen($valueOf) == 3) $valueOf = '0' . $valueOf;
elseif (strlen($valueOf) == 2) $valueOf = '00' . $valueOf;
elseif (strlen($valueOf) == 1) $valueOf = '000' . $valueOf;
return $valueOf; # currently outputs 5837

什么 Java 源代码缺少我的 PHP 代码?

问题是由以下差异引起的:

  • 在 Java 字符串操作charAt以 integer 类型的char形式返回结果,这是一个从 0 到 65535 的无符号 integer。
  • 在 PHP 字符串索引操作[]将结果作为字符返回。

因此,在 Java 中, this.input.charAt(0)返回一个 ASCII 码“F”,即 70。在 PHP 中, $input[0]返回一个字符“F”,不能直接转换为 int。 因此,在 PHP (int)('F')中仅为 0。为了在 PHP 中获取符号的 ASCII 码,请使用ord() 例如:

$input = "F999"; # should output 2360

$charAt = (((ord($input[0]) * 5) * 2) - 698) + ord($input[1]);
$charAt2 = ((((ord($input[2]) * 5) * 2) + $charAt) + ord($input[3])) - 528;
$charAt2 = (($charAt2 << 3) - $charAt2) % 100;
$valueOf = strval(((((((259 % $charAt) % 100) * 5) * 5) * 4) + (((($charAt2 % 10) * 5) * 2) + ((int) floor((double) ($charAt2 / 10))))));
if (strlen($valueOf) == 3) $valueOf = '0' . $valueOf;
elseif (strlen($valueOf) == 2) $valueOf = '00' . $valueOf;
elseif (strlen($valueOf) == 1) $valueOf = '000' . $valueOf;
return $valueOf;

是一个演示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM