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
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With