将 Number 类型缩小为 UInt32 的问题

问题描述

所以我有一个我之前用 C# 编写的代码,我正在尝试将其转换为 JS。 但是,我在 JS 中将我的 Number 类型缩小到 UInt32 Range 时遇到了一个奇怪的问题。 但是,如果我在 C# 或 Object Pascal(具有本机 UInt32 类型的语言)中实现相同的代码,则会得到不同的结果。 有人可以告诉我如何获得与 JS 中的 C# 代码一致的结果。

为简单起见,我使用定义的常量来显示问题。

我的代码的结果是

JS:2444377276

C# 和 Object Pascal:2444377275

function modulo(a,b) {
    return a - Math.floor(a / b) * b;
}

function ToInteger(x) {
    x = Number(x);
    return x < 0 ? Math.ceil(x) : Math.floor(x);
}

function ToUint32(x) {
    return modulo(ToInteger(x),Math.pow(2,32));
}

let a = (1207988537 * 16777619);
console.log(a >>> 0);
let uu = new Uint32Array([a]);
console.log(uu[0]);
console.log(ToUint32(a));
// will only work in ES2020 upwards but produces same result as other JS solutions above
//console.log(BigInt.asUintN(32,BigInt(a)));

C# 代码

using System;
 
public class Test
{
    public static void Main()
    {
        // your code goes here
        unchecked
        {
            uint a = (uint)(1207988537 * 16777619); 
            Console.WriteLine(a);
        }
 
    }
}

对象帕斯卡代码

{$MODE DELPHI}
program ideone;
var
    a: UInt32;
begin
    (* your code goes here *)
     a := UInt32(1207988537 * 16777619); 
    Writeln(a);
end.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)