Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String To Binary in C [closed]

Tags:

im trying to convert string to binary in C. This function must be return a string(char *) like "010010101" etc. Also i want to print what returned. I cant be sure about this code

FUNCTION

char* stringToBinary(char* s)
{
    if(s == NULL) return 0; /* no input string */
    char *binary = malloc(sizeof(s)*8);
    strcpy(binary,"");
    char *ptr = s;
    int i;

    for(; *ptr != 0; ++ptr)
    {

        /* perform bitwise AND for every bit of the character */
        for(i = 7; i >= 0; --i){
            (*ptr & 1 << i) ? strcat(binary,"1") : strcat(binary,"0");
        }


    }
    
    return binary;
}
like image 248
Berkin Akaydın Avatar asked Dec 29 '16 17:12

Berkin Akaydın


1 Answers

Your code seems to be mostly fine. You are only really mallocing the wrong amount. Here it is wth the corrections:

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

char* stringToBinary(char* s) {
    if(s == NULL) return 0; /* no input string */
    size_t len = strlen(s);
    char *binary = malloc(len*8 + 1); // each char is one byte (8 bits) and + 1 at the end for null terminator
    binary[0] = '\0';
    for(size_t i = 0; i < len; ++i) {
        char ch = s[i];
        for(int j = 7; j >= 0; --j){
            if(ch & (1 << j)) {
                strcat(binary,"1");
            } else {
                strcat(binary,"0");
            }
        }
    }
    return binary;
}

Sample runs:

"asdf"           => 01100001011100110110010001100110
"tester"         => 011101000110010101110011011101000110010101110010
"Happy New Year" => 0100100001100001011100000111000001111001001000000100111001100101011101110010000001011001011001010110000101110010
like image 113
gowrath Avatar answered Sep 24 '22 10:09

gowrath