4 ms·
In the previous discussion someone lamented they wished they could do this in JavaScript[0]. Nowadays we have TextDecoder and BigInt64Array so I'm pretty sure
by vanderZwan 4y ago
In the previous discussion someone lamented they wished they could do this in JavaScript[0].
Nowadays we have TextDecoder and BigInt64Array so I'm pretty sure we actually could do it[1][2].
I doubt it would be faster than calling <number>.toString(2), but in principle we could port this.
[0] https://news.ycombinator.com/item?id=10517332 https://news.ycombinator.com/item?id=10517332
[1] https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder
[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt64Array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- Mr_Modulo 4y ago<number>.toString(2) Wouldn't be quite right because the output needs to be padded out with zeros.
- vanderZwan 4y agoOh, right, good catch! So <number>.toString(2).padStart(8, "0") then. I still expect it to be faster than this clever hack though. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- vanderZwan 4y agoHere we go: const toBinary = (() => { const u64 = new BigUint64Array(1); const u8 = new Uint8Array(u64.buffer) u8[0] = 255; const decoder = new TextDecoder(); return (number) => { u64[0] = 0n; u8[0] = number; // We're assuming little-endian architectures u64[0] = (((u64[0] * 0x8040201008040201n) >> 7n) & 0x0101010101010101n) + 0x3030303030303030n return decoder.decode(u8) }; })()