How to convert binary digits to a byte array in TypeScript

1 Answer

0 votes
function binaryToByteArray(binaryString: string): number[] {
    if (binaryString.length % 8 !== 0) {
        throw new Error("Binary string length must be a multiple of 8.");
    }

    const byteList: number[] = [];
    for (let i: number = 0; i < binaryString.length; i += 8) {
        const byteSegment: string = binaryString.slice(i, i + 8);
        const byteValue: number = parseInt(byteSegment, 2);
        byteList.push(byteValue);
    }

    return byteList;
}

const binaryString = "10101110111010101110101001001011";

try {
    const byteList = binaryToByteArray(binaryString);
    console.log("Byte List:", ...byteList);
} catch (e: any) {
    console.error("Error:", e.message);
}
  
  
 
/*
run:
 
"Byte List:",  174,  234,  234,  75 
 
*/
 

 



answered Aug 4, 2025 by avibootz
...