-1

im doing some stuff in javaScript and therefore need to convert a Text String to Decimal .

The php code that i used was:

function to_number($data)
 {
  $base = "256";
  $radix = "1";
  $result = "0";
  for($i = strlen($data) - 1; $i >= 0; $i--)
  {
   $digit = ord($data{$i});
   $part_res = bcmul($digit, $radix);
   $result = bcadd($result, $part_res);
   $radix = bcmul($radix, $base);
  }
  return $result;
  }

since i need to do it in Javascript i tried to convert The String into Hex and then into a Decimal String :

/// String into Hex
function toHex(str) {
    var hex = '';
    var i = 0;
    while(str.length > i) {
        hex += ''+str.charCodeAt(i).toString(16);
        i++;
    }
    return hex;
}

//// Hex into Dec

function h2d(s) {

function add(x, y) {
    var c = 0, r = [];
    var x = x.split('').map(Number);
    var y = y.split('').map(Number);
    while(x.length || y.length) {
        var s = (x.pop() || 0) + (y.pop() || 0) + c;
        r.unshift(s < 10 ? s : s - 10); 
        c = s < 10 ? 0 : 1;
    }
    if(c) r.unshift(c);
    return r.join('');
}

var dec = '0';
s.split('').forEach(function(chr) {
    var n = parseInt(chr, 16);
    for(var t = 8; t; t >>= 1) {
        dec = add(dec, dec);
        if(n & t) dec = add(dec, '1');
    }
});
return dec;
}

Everything works fine and both php and javascript code returns exact same result when i feed them with a regular String like :

thisisasimplestring

but when feeding an input like this:

�ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ�!µ?ŲÀ]).-PSH9Ó·ÂÞ

or even this:

�ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ�yohoo

the result of javascript code will be diffrent from php. i need a result same as php.

Any idea? im looking for help

dudu
  • 19
  • 4
  • Hard to understand what exactly the issue is... but maybe it has to do with the "big int" side of things. JavaScript can cope with 53-bit integers only. Though I'm not sure why unicode characters would need anything that large. – Whothehellisthat May 04 '17 at 19:35
  • Thank you for your comment. although i solved the problem with another solution, but for the refrence its because of the way that javascript handle the characters, i suggest reading this article : https://mathiasbynens.be/notes/javascript-unicode – dudu May 05 '17 at 06:55

1 Answers1

0

although i solved the problem with another solution, but for the refrence its because of the way that javascript handle the characters (characters like those i need) , so

str.charCodeAt(i)

won't return a correct code point for that character.

i suggest reading this article : http://mathiasbynens.be/notes/javascript-unicode

dudu
  • 19
  • 4