UNPKG

@thi.ng/binary

Version:

100+ assorted binary / bitwise operations, conversions, utilities, lookup tables

55 lines (54 loc) 1.91 kB
const F64 = new Float64Array(1); const F32 = new Float32Array(F64.buffer); const U8 = new Uint8Array(F64.buffer); const I32 = new Int32Array(F64.buffer); const U32 = new Uint32Array(F64.buffer); const IS_LE = (U32[0] = 1, U8[0] === 1); const floatToIntBits = (x) => (F32[0] = x, I32[0]); const floatToUintBits = (x) => (F32[0] = x, U32[0]); const intBitsToFloat = (x) => (I32[0] = x, F32[0]); const uintBitsToFloat = (x) => (U32[0] = x, F32[0]); const floatToIntBits64 = (x) => (F64[0] = x, IS_LE ? [I32[1], I32[0]] : [I32[0], I32[1]]); const floatToUintBits64 = (x) => (F64[0] = x, IS_LE ? [U32[1], U32[0]] : [U32[0], U32[1]]); const intBitsToFloat64 = (hi, lo) => { IS_LE ? (I32[1] = hi, I32[0] = lo) : (I32[0] = hi, I32[1] = lo); return F64[0]; }; const uintBitsToFloat64 = (hi, lo) => { IS_LE ? (U32[1] = hi, U32[0] = lo) : (U32[0] = hi, U32[1] = lo); return F64[0]; }; const floatToSortableInt = (x) => { if (x === 0) return 0; const i = floatToIntBits(x); return x < 0 ? ~i | 1 << 31 : i; }; const __f2u = (x, n, p) => x < 0 ? x < -1 ? n : x * n : x > 1 ? p : x * p; const f32u8 = (x) => __f2u(x, 128, 127) & 255; const f32u16 = (x) => __f2u(x, 32768, 32767) & 65535; const f32u24 = (x) => __f2u(x, 8388608, 8388607) & 16777215; const f32u32 = (x) => __f2u(x, 2147483648, 2147483647) >>> 0; const u8f32 = (x) => (x &= 255, (x | (x >> 7) * 4294967040) / (127 + (x >> 7))); const u16f32 = (x) => (x &= 65535, (x | (x >> 15) * 4294901760) / (32767 + (x >> 15))); const u24f32 = (x) => (x &= 16777215, (x | (x >> 23) * 4278190080) / (8388607 + (x >> 23))); const u32f32 = (x) => (x | 0) / (2147483647 + (x >>> 31)); export { IS_LE, f32u16, f32u24, f32u32, f32u8, floatToIntBits, floatToIntBits64, floatToSortableInt, floatToUintBits, floatToUintBits64, intBitsToFloat, intBitsToFloat64, u16f32, u24f32, u32f32, u8f32, uintBitsToFloat, uintBitsToFloat64 };