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
Answer from gowrath on Stack Overflow
Top answer
1 of 3
8

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
2 of 3
2

Without any assumptions about the input, just printing the bits in the bytes:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
char *stringToBinary(char *s)
{
  if (s == NULL) {
    // NULL might be 0 but you cannot be sure about it
    return NULL;
  }
  // get length of string without NUL
  size_t slen = strlen(s);

  // we cannot do that here, why?
  // if(slen == 0){ return s;}

  errno = 0;
  // allocate "slen" (number of characters in string without NUL)
  // times the number of bits in a "char" plus one byte for the NUL
  // at the end of the return value
  char *binary = malloc(slen * CHAR_BIT + 1);
  if(binary == NULL){
     fprintf(stderr,"malloc has failed in stringToBinary(%s): %s\n",s, strerror(errno));
     return NULL;
  }
  // finally we can put our shortcut from above here
  if (slen == 0) {
    *binary = '\0';
    return binary;
  }
  char *ptr;
  // keep an eye on the beginning
  char *start = binary;
  int i;

  // loop over the input-characters
  for (ptr = s; *ptr != '\0'; ptr++) {
    /* perform bitwise AND for every bit of the character */
    // loop over the input-character bits
    for (i = CHAR_BIT - 1; i >= 0; i--, binary++) {
      *binary = (*ptr & 1 << i) ? '1' : '0';
    }
  }
  // finalize return value
  *binary = '\0';
  // reset pointer to beginning
  binary = start;
  return binary;
}


int main(int argc, char **argv)
{
  char *output;
  if (argc != 2) {
    fprintf(stderr, "Usage: %s string\n", argv[0]);
    exit(EXIT_FAILURE);
  }
  // TODO: check argv[1]
  output = stringToBinary(argv[1]);
  printf("%s\n", output);

  free(output);
  exit(EXIT_SUCCESS);
}
🌐
Computerscienceai
computerscienceai.com › 2020 › 10 › string-to-binary-c.html
Computer Science AI: C Program to Convert Text String to Binary
February 4, 2021 - Here is the source code to convert text to binary in c. #include <stdio.h> #include <string.h> int main(){ int i; char *string = "String to Binary In C"; for(i=0;i<8*strlen(string);i++) printf("%d",0 != (string[i/8] & 1 << (~i&7))); printf("\n"); }
🌐
YouTube
youtube.com › kmengmath(ក្មេងគណិត)
how to convert String to binary in c/c++ Programming speak khmer - YouTube
AboutPressCopyrightContact usCreatorsAdvertiseDevelopersTermsPrivacyPolicy & SafetyHow YouTube worksTest new featuresNFL Sunday Ticket · © 2024 Google LLC
Published: February 14, 2021
Views: 812
Discussions

Converting C string to binary representation - Stack Overflow
In ANSI C, how do we convert a string in to an array of binary bytes? All the googling and searching gives me answers for C++ and others and not C. One idea I had was to convert the string into A... More on stackoverflow.com
🌐 stackoverflow.com
c - How to convert a string to binary? - Stack Overflow
I'm working on a C project and I have some instructions of type: add $1 $2 $3 So I'm reading the line as a string, parsing through it and have a corresponding integer for add, say - 2. Could anyone More on stackoverflow.com
🌐 stackoverflow.com
November 8, 2011
string - Conversion of Char to Binary in C - Stack Overflow
I am trying to convert a character to its binary representation (so character --> ascii hex --> binary). I know to do that I need to shift and AND. However, my code is not working for some reason. Here is what I have. *temp points to an index in a C string. More on stackoverflow.com
🌐 stackoverflow.com
c - How convert string to binary - Stack Overflow
Im cant understand whats wrong with my code. All start to work good, but when my phrase "Hello, how are you" compiled, it start to print some other numbers and symbols. Thank you in advance! More on stackoverflow.com
🌐 stackoverflow.com
🌐
C-programming-simple-steps
c-programming-simple-steps.com › home › number systems › text to binary
ASCII text to binary - C Programming
We need to take the code of each character in decimal and convert it to binary. The input is basically a string, so taking each character from it is no problem.
🌐
YouTube
youtube.com › cambo its
How to Convert String to Binary c and c++ - YouTube
Subscribe this channel for more video. THANK YOU
Published: July 4, 2019
Views: 1K
Find elsewhere
🌐
YouTube
youtube.com › watch
C Program To Convert Word into Binary - YouTube
Convert Any String or Word into Binary Values using shift operators. For Loop, if else statement
Published: August 23, 2017
🌐
C For Dummies
c-for-dummies.com › blog
From String to Binary | C For Dummies Blog
April 14, 2018 - Type up to a 16-digit binary value: 1111111111111111 That's 65535 Type up to a 16-digit binary value: 01110000110000001 That's 57729 Type up to a 16-digit binary value: 1111 That's 15 Type up to a 16-digit binary value: 11110000 That's 240 · The code works when the string is shorter than 16 characters, accurately reflecting the value.
🌐
RapidTables
rapidtables.com › convert › number › string-to-binary.html
String to Binary Converter
Enter ASCII/Unicode text string and press the Convert button (e.g enter "Example" to get "01000101 01111000 01100001 01101101 01110000 01101100 01100101"): ... Use ASCII table to get ASCII code from character.
🌐
Blogger
naimcprogram.blogspot.com › 2016 › 02 › c-program-to-convert-text-string-to.html
C Program to Convert Text String to Binary - NAIMCPROGRAM
Solution: #include <stdio.h> #include <string.h> int main(){ int i; char *word = "Hello Word"; for(i=0;i<8*strlen(word);i++) printf("%d",0 != (word[i/8] & 1 << (~i&7))); printf("\n"); } ... C Program to accept 5 names from user & store these names into an array. Sort these array elements in alphabetical order · C Program to search an element using linear search or binary search (menu driven program)
🌐
Cprogramming
faq.cprogramming.com › cgi-bin › smartfaq.cgi
Converting a string to binary - Cprogramming.com - FAQ
How to begin Get the book · C tutorial C++ tutorial Game programming Graphics programming Algorithms More tutorials
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › convert-string-binary-sequence
Convert String into Binary Sequence - GeeksforGeeks
// C++ program to convert // string into binary string #include <bits/stdc++.h> using namespace std; // utility function void strToBinary(string s) { int n = s.length(); for (int i = 0; i <= n; i++) { // convert each char to // ASCII value int ...
Published: August 4, 2022
Top answer
1 of 3
38

We show up two functions that prints a SINGLE character to binary.

void printbinchar(char character)
{
    char output[9];
    itoa(character, output, 2);
    printf("%s\n", output);
}

printbinchar(10) will write into the console

    1010

itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".

The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.

void printbincharpad(char c)
{
    for (int i = 7; i >= 0; --i)
    {
        putchar( (c & (1 << i)) ? '1' : '0' );
    }
    putchar('\n');
}

printbincharpad(10) will write into the console

    00001010

Now i present a function that prints out an entire string (without last null character).

void printstringasbinary(char* s)
{
    // A small 9 characters buffer we use to perform the conversion
    char output[9];

    // Until the first character pointed by s is not a null character
    // that indicates end of string...
    while (*s)
    {
        // Convert the first character of the string to binary using itoa.
        // Characters in c are just 8 bit integers, at least, in noawdays computers.
        itoa(*s, output, 2);

        // print out our string and let's write a new line.
        puts(output);

        // we advance our string by one character,
        // If our original string was "ABC" now we are pointing at "BC".
        ++s;
    }
}

Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:

1000001
1000010
110001
2 of 3
8
unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}

printf("\n");

Explanation:

With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

🌐
Stack Overflow
stackoverflow.com › questions › 74649265 › how-convert-string-to-binary
c - How convert string to binary - Stack Overflow
You're not allocating memory to string which you are passing. which leads to UB. I removed string size parameter in function encode_string · #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> void encode_string(const char string[]) { size_t len = strlen(string); char *binary = malloc(len*8 + 1); //each char is one byte (8 bits) and + 1 at the end for null terminator for(int j = 0; j <= len; j++){ printf("%c: ", string[j]); for( int i = 7; i >= 0; i-- ) { printf( "%d", ( string[j] >> i ) & 1 ?
🌐
Reddit
reddit.com › r/cs50 › pset 2- bulbs need help converting string to binary
r/cs50 on Reddit: PSET 2- Bulbs need help converting string to binary
May 6, 2023 -

I need help to figure out how to convert string to binary. I though my code would work but it didn't

I don't quite get why this isn't working.

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

const int BITS_IN_BYTE = 8;

void print_bulb(int bit);

int main(void)
{
    string message = get_string("Message? ");

    string binary = "";
    for (int i = 0; i < strlen(message); i++)
    {
        if (message[i] % 2 == 0)
        {
           binary = 0 + "binary";
        }
        else if (message[i] % 2 == 1)
        {
            binary = 1 + "binary";
        }
    }
    printf("%s\n", binary);
}

void print_bulb(int bit)
{
    if (bit == 0)
    {
        // Dark emoji
        printf("\U000026AB");
    }
    else if (bit == 1)
    {
        // Light emoji
        printf("\U0001F7E1");
    }
}
Top answer
1 of 2
3
Hi! :) I'm new like you, I am doing week 4 at this moment. I am afraid you have to start this task from beginning :( look at the void print_bulb function, you didn't used it once in your code. as far as i can see u tried to create string binary to create binary sequence of your word but it is wrong. If for example i would use word "Hi!" your code takes first letter H which ascii value is 72, than it checks modulo 2 of 72 which is 0. The binary representation of 0 is 0, not 72. In that case "Hi!" is translated into 011 :( So at this moment if I were You, I would start of creating a code that takes only one letter, checks its value, and create a binary representation in 8 bits! Where letter 'H' = 72 Now we have to create 8 bit binary representation. 0 1 0 0 1 0 0 0 - number 72 in binary 8 bit 7 6 5 4 3 2 1 0 - exponent of number 2 power in bit positions so look from left to right first 1 is in 6th position = 2 power 6 = 64, second 1 is in 3rd position = 2 power 3 = 8, 8 + 64 = 72 = 'H'. I created loop that checks from 2^7 to 2^0 if value of my letter/sign is greater than power i'm checking. I don't want to spoil to much. If you need further help, i ll try my best :)
2 of 2
1
After: string binary = ""; What is binary? How much storage does it have? Can you tell? What is we fix the broken part of CS50 (hiding pointers behind a typedef) and make it explicit what you are dealing with: char *binary = "";` Again, what is binary? An array? A pointer? If a pointer, a pointer to what? (hint: "" is a string-literal, which resides in read-only memory) How do you expect to modify it? Why not allocate strlen(message) + 1 characters for binary (or use a VLA) so you have usable storage to fill? (if you indeed need storage) What are 0 and 1 in binary = 1 + "binary";? (offsets) But to what? Does "binary" look like "" but longer? Is it a string-literal as well? On access, what type does a string-literal have? (hint: C-Standard 6.3.2.1 (paragraph 3) https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2596.pdf#subsubsection.6.3.2.1 ) Also, if you include limits.h the CHAR_BIT macro provides the number of bits-per-byte.
🌐
Reddit
reddit.com › r/learnprogramming › help needed c, hex string to binary string.
r/learnprogramming on Reddit: Help needed C, hex string to binary string.
April 3, 2014 -

Learning C currrently could use a little help. I'm still new to programming so the simpler the better.

So I'm having a lot of difficulty wrapping my head around this problem.

I'm trying to write a function that will convert a hexadecimal string (0123456789abcdef) into binary (0000 0001 .......).

Been stuck for several hours trying to figure out a solution. Any help will be greatly appreciated.

🌐
Code Beautify
codebeautify.org › string-binary-converter
String to Binary Converter Online tool
This tool allows loading the String URL, which loads String and converts to Binary Numeral System. Click on the URL button, Enter URL and Submit.
🌐
Codemiles
codemiles.com › c-examples › convert-string-into-binary-t2882.html
convert string into binary - C++ examples - Codemiles
November 13, 2008 - A simple program that converts a string into its binary representation.: