Search code examples
javascriptc#uint

I can't get proper uint32 number in javascript


i am trying to convert a long number to unit in JavaScript, but the result i got it different from the one i already have in c#.

c#:

var tt=431430059159441001;
var t=(UInt32)tt;//1570754153

js:

var arr =new Uint32Array(1);
arr[0]=431430059159441001;//1570754176

so could any body explain why there is difference.


Solution

  • That's because your number literal is rather a 64 bit integer, and that cannot be represented in JavaScripts regular Number type. The number type is a 64-bit precision floating point number, which can only represent integer values up to around 2**53. So I would recommend to just not use such a huge number literal.

    A recent development in the JavaScript world is BigInts. If you can afford to use them, then your code is easy to fix:

    var t = Number(BigInt.asUintN(32, 431430059159441001n));
    console.log(t); // 1570754153