Thursday, 18 May 2017

Java number precision in Javascript

I have the following code in Java that convert Hex values to Long numbers, in the example I used the value: 'B4EEB49B04C0'

public static long HexStr2Long(String value)
{
    value = value.toUpperCase();
    long result = 0;
    for (int i = 0; i < value.length(); i++)
    {
        int x = value.length() - i - 1;
        char ch = value.charAt(i);
        result += keys.indexOf(ch) * Pow(exponent, x);
    }
    return result;
}

public static long Pow(long baseNo, long x)
{
    long value = 1;
    while (x > 0)
    {
        value = value * baseNo;
        x--;
    }
    return value;
}

public static void main(String[] args) {
    long result = HexStr2Long("B4EEB49B04C0");
    System.out.print("resultado: "+result+"\n");
}

The result is: 1463925582232863984

Now, I created the equivalent code in Javascript:

pow = function(baseNo, x){
  var value = 1;
  while(x > 0){
    value = value * baseNo;
    x--;
  }

  return value;
}

hexStr2Long = function(val){
 var keys = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 var exponent = keys.length;

 val = val.toUpperCase();
 var result = 0;
 for (var i = 0; i < val.length; i++) {
    var x = val.length - i - 1;
    var ch = val.charAt(i);
    result +=  keys.indexOf(ch) * Math.pow(exponent, x);
 }

 return result;
}
var r = hexStr2Long(wifimac);
console.log('Result: '+r);

The result is: 1463925582232864000, this in wrong, it has to be the same as Java code.

How can I accomplish that? I've already tried to use the library (BigNumber) but without success.



via isaiasmac

No comments:

Post a Comment