/** * Converts a binary string (containing only '0' and '1' characters) to bytes. * The binary string length must be a multiple of 8. * @param binary - Binary string to convert (e.g., '11111111' for 255) * @returns Uint8Array representation of the binary string * @throws {TypeError} If binary string contains non-binary characters * @throws {Error} If binary string length is not a multiple of 8 */ export function bin_to_bytes ( binary : string ) : Uint8Array { // Validate that the string only contains '0' and '1' characters if (!/^[01]*$/.test(binary)) { throw new TypeError('Binary string must contain only 0 and 1 characters') } const bins = binary.split('').map(Number) if (bins.length % 8 !== 0) { throw new Error(`Binary array is invalid length: ${binary.length}`) } const bytes = new Uint8Array(bins.length / 8) for (let i = 0, ct = 0; i < bins.length; i += 8, ct++) { let byte = 0 for (let j = 0; j < 8; j++) { byte |= (bins[i + j] << (7 - j)) } bytes[ct] = byte } return bytes } /** * Converts bytes to a binary string representation. * Each byte becomes 8 binary characters (0 or 1). * @param bytes - Uint8Array to convert * @returns Binary string representation (e.g., '11111111' for [255]) * @throws {Error} If any byte value is outside 0-255 range */ export function bytes_to_bin ( bytes : Uint8Array ) : string { // Create a binary array that is sized to (number of bytes) * 8. const bin = new Array(bytes.length * 8) let count = 0 // Iterate through each number in the byte array. for (const num of bytes) { if (num > 255) { // Throw an error on invalid number ranges. throw new Error(`Invalid byte value: ${num}. Byte values must be between 0 and 255.`) } // Convert the current number into bits using bitwise operations. for (let i = 7; i >= 0; i--, count++) { bin[count] = (num >> i) & 1 } } // Return the complete binary array. return bin.join('') }