简体   繁体   English

为什么 JS 中的数字 10_000_000_000 在 webassembly 中变成 1410065408?

[英]Why number 10_000_000_000 in JS becomes 1410065408 in webassembly?

I made a very simple wasm with the following text format.我用以下文本格式做了一个非常简单的wasm。 The function just return the i32 parameter. function 只是返回 i32 参数。

(module
 (type $i32_=>_i32 (func (param i32) (result i32)))
 (memory $0 0)
 (export "sum" (func $assembly/index/sum))
 (export "memory" (memory $0))
 (func $assembly/index/sum (param $0 i32) (result i32)
  local.get $0
 )
)

and use the export function in nodejs:并在nodejs中使用导出function:

const mod = await (...load wasm here)
console.log(mod.sum(10_000_000_000));   //1410065408

why it outputs 1410065408?为什么它输出1410065408?

Well, you're usiung an i32 as a parameter, which has a max value of 2147483647 , and you're passing in 10000000000 .好吧,您使用i32作为参数,其最大值为2147483647 ,并且您传入10000000000 It's either truncating or overflowing the value to fit inside an integer.它要么截断要么溢出值以适合 integer。

I suggest using an i64 if your use case truly needs to handle numbers this big如果您的用例确实需要处理这么大的数字,我建议使用i64

(Jam is right. Just filling in the tedious details) (果酱是对的。只是填写繁琐的细节)

Wasm's i32 type is 4 bytes. Wasm 的i32类型是 4 个字节。 (4*8) (4*8)

10_000_000_000 10 is 2_540B_E400 16 (or 0x2540BE400) and that's 5 bytes, so JavaScript silently truncates it to 4 bytes (the leading 2_ is lost) when passing it to the Wasm function. 10_000_000_000 10 IS IS 2_540B_E400 16 (或0x2540BE400),这是5个字节,因此Z686155AF75A60A0A0A0F6E9D80C1F7EDD3E9Z默默地将其截断为4个字节(丢失了2_

So we get 540B_E400 16 which is 1_410_065_408 10 which is exactly the result you are seeing.所以我们得到 540B_E400 16即 1_410_065_408 10 ,这正是您所看到的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM