From 529a74ee6f41943c42d5955a32b75d76ccba783c Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Tue, 30 Jun 2026 14:59:41 -0700 Subject: [PATCH] Update binary-to-byte converter. --- src/lib/convert/bin.ts | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/lib/convert/bin.ts b/src/lib/convert/bin.ts index 5ca0876..6da5275 100644 --- a/src/lib/convert/bin.ts +++ b/src/lib/convert/bin.ts @@ -8,13 +8,20 @@ export const bin = Object.freeze({ * @param {string} bin - String to convert * @returns {Uint8Array} Byte array representation of the input string */ - toBytes (bin: string): Uint8Array { - const bytes: number[] = [] - while (bin.length > 0) { - const bits = bin.substring(0, 8) - bytes.push(parseInt(bits, 2)) - bin = bin.substring(8) + toBytes (bin: string, padding: number = 1): Uint8Array { + if (typeof bin !== 'string' || !/^[01]+$/i.test(bin)) { + throw new TypeError('Invalid string when converting bin to bytes', { cause: bin }) } - return new Uint8Array(bytes) + if (typeof padding !== 'number' || padding < 1 || padding > 0xffffffff) { + throw new TypeError('Invalid padding when converting bin to bytes', { cause: padding }) + } + const pad = bin.length & 7 + if (pad) bin = bin.padStart(bin.length + 8 - pad, '0') + const byteLength = bin.length >> 3 + const diff = padding - byteLength + const offset = diff & ~(diff >> 31) + const bytes = new Uint8Array(byteLength + offset) + bytes.set(bin.match(/.{8}/g)?.map(b => parseInt(b, 2)) ?? [], offset) + return bytes }, }) -- 2.52.0