How to convert binary code to text in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *bin2text(const char *bin_txt) {
    int len = strlen(bin_txt) / 8;  // Calculate the number of characters in the binary string
    char *text = (char *)malloc((len + 1) * sizeof(char)); // Allocate memory for the text
    text[len] = '\0'; // Null-terminate the string
    
    for (int i = 0; i < len; i++) {
        char binary[9]; // Temporary array to hold an 8-bit binary chunk
        strncpy(binary, bin_txt + i * 8, 8); // Copy 8 bits from the binary string
        binary[8] = '\0'; // Null-terminate the binary chunk

        // Convert the binary chunk to a decimal value and then to a character
        text[i] = strtol(binary, NULL, 2);
    }
    
    return text;
}

int main() {
    const char *bin_txt = "0101000001110010011011110110011101110010011000010110110101101101011010010110111001100111";
    char *text = bin2text(bin_txt);

    printf("%s\n", text);

    free(text);

    return 0;
}



/*
run:

Programming

*/

 



answered Apr 14, 2025 by avibootz

Related questions

1 answer 98 views
1 answer 189 views
1 answer 112 views
112 views asked Nov 17, 2024 by avibootz
1 answer 92 views
1 answer 90 views
90 views asked Nov 17, 2024 by avibootz
1 answer 100 views
...