最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - I can't get proper uint32 number in javascript - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Jan 24, 2019 at 17:11 Ghaith Sabbagh asked Jan 24, 2019 at 15:52 Ghaith SabbaghGhaith Sabbagh 632 silver badges9 bronze badges 1
  • 1 Your code gives CS0221 Constant value '431430059159441001' cannot be converted to a 'uint' (use 'unchecked' syntax to override). Please update your question and add details what actually you are doing with working examples. – Renatas M. Commented Jan 24, 2019 at 16:04
Add a ment  | 

3 Answers 3

Reset to default 5

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 remend 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

This is not about uints, but about floats. JavaScript uses floating point numbers, and your number exceeds the maximum range of integers that can safely be represented:

console.log(431430059159441001)

You cannot convert 431430059159441001 to unsigned integer in c#. Max Value of UInt32 is 4294967295. So the var t=(UInt32)431430059159441001; assignment gives Compiler error.

also 431430059159441001 is larger then max value of float number (javascript holds number with float format)

发布评论

评论列表(0)

  1. 暂无评论