How to convert binary digits to a byte array in JavaScript

1 Answer

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

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

    return byteList;
}

const binaryString = "10101110111010101110101001001011";

try {
    const byteList = binaryToByteArray(binaryString);
    console.log("Byte List:", ...byteList);
} catch (e) {
    console.error("Error:", e.message);
}



/*
run:

Byte List: 174 234 234 75

*/

 



answered Aug 4, 2025 by avibootz
...