Search code examples
cstringbinarychar8-bit

Converting massive binary input string into character string C


I'm not familiar with C at all so this might be a simple problem to solve. I'm trying to take an input char* array of binary character sequences, ex. "0100100001101001", and output its relative string ("Hi"). The problem I'm having is coming up with a way to split the input into seperate strings of length 8 and then convert them individually to ulimately get the full output string.

char* binaryToString(char* b){
    char binary[8];
    for(int i=0; i<8; ++i){
    binary[i] = b[i];
}
printf("%s", binary);
}

I'm aware of how to convert 8-bit into its character, I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

Any help is appreciated... thanks!


Solution

  • From what I can tell, your binaryToString() function does not do what you'd want it to. The print statement just prints the first eight characters from the address pointed to by char* b.

    Instead, you can convert the string of 8 bits to an integer, utilizing a standard C function strtol(). There's no need to convert any further, because binary, hex, decimal, etc, are all just representations of the same data! So once the string is converted to a long, you can use that value to represent an ASCII character.

    Updating the implementation (as below), you can then leverage it to print a whole sequence.

    #include <stdio.h>
    #include <string.h>
    
    void binaryToString(char* input, char* output){
    
        char binary[9] = {0}; // initialize string to 0's
    
        // copy 8 bits from input string
        for (int i = 0; i < 8; i ++){
            binary[i] = input[i];    
        }
    
        *output  = strtol(binary,NULL,2); // convert the byte to a long, using base 2 
    }
    
    int main()
    {
    
        char inputStr[] = "01100001011100110110010001100110"; // "asdf" in ascii 
        char outputStr[20] = {0}; // initialize string to 0's
    
        size_t iterations = strlen(inputStr) / 8; // get the # of bytes
    
        // convert each byte into an ascii value
        for (int i = 0; i < iterations; i++){
            binaryToString(&inputStr[i*8], &outputStr[i]);
        }
    
        printf("%s", outputStr); // print the resulting string
        return 0;
    }
    

    I compiled this and it seems to work fine. Of course, this can be done cleaner and safer, but this should help you get started.