* @param {string} bin - String to convert
* @returns {Uint8Array} Byte array representation of the input string
*/
- toBytes (bin: string): Uint8Array<ArrayBuffer> {
- 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<ArrayBuffer> {
+ 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
},
})