How to convert binary digits to a byte array in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h> // uint8_t
#include <string.h>

// Converts a binary string to a byte array
uint8_t* binaryToByteArray(const char* binaryString, size_t* outSize) {
    size_t length = strlen(binaryString);

    // Ensure the binary string length is a multiple of 8
    if (length % 8 != 0) {
        fprintf(stderr, "Error: Binary string length must be a multiple of 8.\n");
        *outSize = 0;
        return NULL;
    }

    size_t byteCount = length / 8;
    uint8_t* byteArray = (uint8_t*)malloc(byteCount);
    if (!byteArray) {
        fprintf(stderr, "Error: Memory allocation failed.\n");
        *outSize = 0;
        return NULL;
    }

    for (size_t i = 0; i < byteCount; ++i) {
        uint8_t byte = 0;
        for (size_t j = 0; j < 8; ++j) {
            char bit = binaryString[i * 8 + j];
            if (bit != '0' && bit != '1') {
                fprintf(stderr, "Error: Invalid character in binary string.\n");
                free(byteArray);
                *outSize = 0;
                return NULL;
            }
            byte = (byte << 1) | (bit - '0');
        }
        byteArray[i] = byte;
    }

    *outSize = byteCount;
    return byteArray;
}

int main() {
    const char* binaryString = "10101110111010101110101001001011";
    size_t byteArraySize = 0;

    uint8_t* byteArray = binaryToByteArray(binaryString, &byteArraySize);
    if (byteArray) {
        printf("Byte Array: ");
        for (size_t i = 0; i < byteArraySize; ++i) {
            printf("%d ", byteArray[i]);
        }
        free(byteArray);
    }

    return 0;
}


/*
run:
  
Byte Array: 174 234 234 75 

*/


 



answered Aug 4, 2025 by avibootz
...