Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Last active July 31, 2020 15:41
Show Gist options
  • Select an option

  • Save gkucmierz/b271c6eda444a6ad237db66baf8b0a89 to your computer and use it in GitHub Desktop.

Select an option

Save gkucmierz/b271c6eda444a6ad237db66baf8b0a89 to your computer and use it in GitHub Desktop.
const BYTE = 8;
const BITS = 64;
const SEGMENTS = 8;
const SEGMENT = BITS / SEGMENTS;
const METHODS_MAP = {
8: ['getUint8', 'setUint8', 'getInt8', 'setInt8'],
16: ['getUint16', 'setUint16', 'getInt16', 'setInt16'],
32: ['getUint32', 'setUint32', 'getInt32', 'setInt32'],
};
const [
MAP_GET_U,
MAP_SET_U,
MAP_GET_I,
MAP_SET_I,
] = [0, 1, 2, 3];
const USE_UNSIGNED = false;
const MAP_GET = USE_UNSIGNED ? MAP_GET_U : MAP_GET_I;
const MAP_SET = USE_UNSIGNED ? MAP_SET_U : MAP_SET_I;
const float2bits = (num) => {
const buffer = new ArrayBuffer(BITS/BYTE);
const view = new DataView(buffer);
view.setFloat64(0, num);
const max16i = 2 ** SEGMENT;
const bits = [];
for (let i = 0; i < SEGMENTS; ++i) {
const u16 = view[METHODS_MAP[SEGMENT][MAP_GET]](i);
let b = max16i >> 1;
while (b) {
bits.push(u16 & b ? 1 : 0);
b >>= 1;
}
}
return bits;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment