1

I made a very simple wasm with the following text format. The function just return the i32 parameter.

(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:

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

why it outputs 1410065408?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
KKKKim
  • 11
  • 1
  • 1
    maximum value of defined integer, if you need higher you use int64, which is larger which often makes things more complex – zergski Sep 07 '22 at 00:25

2 Answers2

1

Well, you're usiung an i32 as a parameter, which has a max value of 2147483647, and you're passing in 10000000000. It's either truncating or overflowing the value to fit inside an integer.

I suggest using an i64 if your use case truly needs to handle numbers this big

Jam
  • 476
  • 3
  • 9
1

(Jam is right. Just filling in the tedious details)

Wasm's i32 type is 4 bytes. (4*8)

10_000_000_00010 is 2_540B_E40016 (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.

So we get 540B_E40016 which is 1_410_065_40810 which is exactly the result you are seeing.

zahical
  • 246
  • 3
  • 8