由于以下代码非常简单,并且
功能等同于除法
,这里是
更改位的替代方法
。(此代码是从@T.J.Crowder非常有用的答案中复制和修改的)
//一个大小刚好可以转换为Float64的缓冲区
let buffer=新的ArrayBuffer(8);
//将其视为Int8Array并用8个随机整数填充
让ints=新的Int8Array(缓冲区);
window.crypto.getRandomValues(整数);
//将符号(ints[7][7])设置为0
//指数(ints[7][6]-[6][5])调整到正确的大小
//(除最高位外的所有位)
整数[7]=63;
整数[6]|=0xf0;
//现在将其视为Float64Array,并从中读取一个浮点
let float=新数据视图(缓冲区)。getFloat64(0,真)-1;
document.body。innerHTML=“数字为”+float
解释:
IEEE754双精度
的格式为1个符号位(
ints[7][7]
)、11个指数位(
ints[17][6]到
ints[6][5]
),其余为尾数(保留值)。计算公式为
要将因子设置为1,指数需要为1023。它有11位,因此最高阶位为2048。这需要设置为0,其他位为1
,这是
alternate method of altering the bits
。(此代码是从@T.J.Crowder非常有用的回答中复制和修改的)。
// A buffer with just the right size to convert to Float64
let buffer = new ArrayBuffer(8);
// View it as an Int8Array and fill it with 8 random ints
let ints = new Int8Array(buffer);
window.crypto.getRandomValues(ints);
// Set the sign (ints[7][7]) to 0 and the
// exponent (ints[7][6]-[6][5]) to just the right size
// (all ones except for the highest bit)
ints[7] = 63;
ints[6] |= 0xf0;
// Now view it as a Float64Array, and read the one float from it
let float = new DataView(buffer).getFloat64(0, true) - 1;
document.body.innerHTML = "The number is " + float;
解释:
The format of a IEEE754 double
是1个符号位(
ints[7][7]
),11个指数位(
ints[7][6]
到
ints[6][5]
),其余为尾数(保留值)。计算公式为
要将因子设置为1,指数需要为1023。它有11位,因此最高阶位为2048。这需要设置为0,其他位为1。