【问题标题】:Unexpected negative value in Int32ArrayInt32Array 中出现意外的负值
【发布时间】:2017-09-05 20:12:21
【问题描述】:
const x = new Int32Array(1);

x[0] = 699044815921;
console.log(x[0]);
-1034853327

谁能解释为什么会有一个负数?

【问题讨论】:

  • 因为你没有使用无符号整数数组
  • en.wikipedia.org/wiki/Integer_overflow : "如果变量具有带符号整数类型,程序可能会假设变量始终包含正值。整数溢出会导致值回绕和变为负数,这违反了程序的假设并可能导致意外行为(例如,127 + 1 的 8 位整数加法得到 -128,即 128 的二进制补码)。”
  • 尝试使用 intval() 来解决这个问题。
  • 此外,这个数字甚至太大而无法用 32 位无符号整数表示。
  • 如何解决它并存储大整数?首先要记住使用 float64 来存储

标签: javascript arrays integer


【解决方案1】:

Int32Array 允许每个值 32 位,保留第 32 位(从右侧开始)以指定数字的符号。您尝试拟合的数字是 (699044815921).toString(2).length == 40 位长,因此最左边的 8 位被丢弃,第 32 位被解释为符号位,您将得到结果。

【讨论】:

  • 感谢您的解释。
  • 为了进一步研究,您可以使用二进制常量来查看符号位如何影响数字:let x = new Int8Array(1); x[0] = 0b00000001; console.log(x[0]); x[0] = 0b10000001; console.log('sign bit set', x[0]); x[0] = 0b111110000001; console.log('4 bits overflow', x[0]);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
相关资源
最近更新 更多