How to convert binary digits to a byte vector in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <bitset>
#include <string>
#include <cstdint>

std::vector<uint8_t> binaryToByteVector(const std::string& binaryString) {
    std::vector<uint8_t> byteArray;

    // Ensure the binary string length is a multiple of 8
    size_t length = binaryString.length();
    if (length % 8 != 0) {
        throw std::invalid_argument("Binary string length must be a multiple of 8.");
    }

    // Process each 8-bit chunk
    for (size_t i = 0; i < length; i += 8) {
        std::string byteString = binaryString.substr(i, 8);
        uint8_t byte = static_cast<uint8_t>(std::bitset<8>(byteString).to_ulong());
        byteArray.push_back(byte);
    }

    return byteArray;
}

int main() {
    std::string binaryString = "10101110111010101110101001001011";

    try {
        std::vector<uint8_t> byteArray = binaryToByteVector(binaryString);

        std::cout << "Byte Array: ";
        for (uint8_t byte : byteArray) {
            std::cout << static_cast<int>(byte) << " ";
        }
        std::cout << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}

  
   
/*
run:
  
Byte Array: 174 234 234 75 

*/

 



answered Aug 4, 2025 by avibootz
edited Aug 4, 2025 by avibootz
...