2

Function in javascript:

function int64add(dst, x, y)
{
    var w0 = (x.l & 0xffff) + (y.l & 0xffff);
    var w1 = (x.l >>> 16) + (y.l >>> 16) + (w0 >>> 16);
    var w2 = (x.h & 0xffff) + (y.h & 0xffff) + (w1 >>> 16);
    var w3 = (x.h >>> 16) + (y.l >>> 16) + (w2 >>> 16);
    dst.l = (w0 & 0xffff) | (w1 << 16);
    dst.h = (w2 & 0xffff) | (w3 << 16);
}

I converted this javascript to PHP as: Function in PHP:

function int64add($dst, $x, $y)
{
    $w0 = ($x->l & 0xffff) + ($y->l & 0xffff);
    $w1 = ($x->l >> 16) + ($y->l >> 16) + ($w0 >> 16);
    $w2 = ($x->h & 0xffff) + ($y->h & 0xffff) + ($w1 >> 16);
    $w3 = ($x->h >> 16) + ($y->l >> 16) + ($w2 >> 16);
    $dst->l = ($w0 & 0xffff) | ($w1 << 16);
    $dst->h = ($w2 & 0xffff) | ($w3 << 16);
}

these two function return different output for same input. Tried searching over internet but couldn't find anything. Please help!

In JS:

Input:

dst:

int64{
    h=1779033703,
    l=-205731576
}

x:

int64{
    h=1779033703,
    l=-205731576
}

y:

int64{
    h=1779033703,
    l=-205731576
}

returns:

int64{
    h=-736899889,
    l=-411463152
}

IN PHP:

Input:

dst:

int64{
    h=1779033703,
    l=-205731576
}

x:

int64{
    h=1779033703,
    l=-205731576
}

y:

int64{
    h=1779033703,
    l=-205731576
}

returns:

int64{
    h=-736899891,
    l=-411463152
}

Class int64 in php:

class int64{
    var $h;
    var $l;
    function int64($h,$l){
        $this->h=$h;
        $this->l=$l;
    }
}

Function int64 in js:

    function int64(h,l){
        this.h=h;
        this.l=l;
    }

I want PHP to give output as Javascript. (Javascript is the correct one)

1 Answers1

0

That's because you're not handling the >>> operator properly in PHP. You should make sure to clear the higher bits using & 0xffff after the right shift operation:

$w0 = ($x->l & 0xffff) + ($y->l & 0xffff);
$w1 = (($x->l >> 16) & 0xffff) + (($y->l >> 16) & 0xffff) + (($w0 >> 16) & 0xffff);
$w2 = ($x->h & 0xffff) + ($y->h & 0xffff) + ($w1 >> 16);
$w3 = (($x->h >> 16) & 0xffff) + (($y->l >> 16) & 0xffff) + (($w2 >> 16) & 0xffff);

Doing that gave the same values for me, but they were different from yours; maybe your input values weren't all the same (copy paste mistake?)

object(int64)#1 (2) {
  ["h"]=>
  int(1573309647)
  ["l"]=>
  int(-411463152)
}

As others have mentioned, I would seriously consider using GMP or BCMath.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309