次のコードは非常に単純でfunctionally equivalent to the division methodなので、ここには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ビットを有している、ことが必要で、従って最上位ビットは、これが0に設定する必要2048を与えます他のビットは1になります。
'window.crypto'をサポートするブラウザだけをサポートする必要がありますか? –
@ T.J.Crowder:実際、私の使用例では、Firefoxで十分です。より一般的な、歓び。 –
JavaScriptの浮動小数点数は、64ビットのIEEE-754の数字です(必要な場合は32ビットを得ることができます)。つまり、有効な2進数は53(有効)です。 。ほぼすべての暗号化目的には十分ではありません。 –