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"); }
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 ascii string to binary? - Stack Overflow
I'm trying to convert an ascii string to a binary string in C. I found this example Converting Ascii to binary in C but I rather not use a recursive function. I tried to write an iterative function... 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: ... So I'm reading the line as a string, parsing through it and have a corresponding integer for add, say - 2. Could anyone please tell me how I could convert this to binary in order to write it to a file? More on stackoverflow.com
🌐 stackoverflow.com
November 8, 2011
c - Binary string to integer and integer to binary string - Code Review Stack Exchange
I am working through K&R for review and I thought that I would write some of my own routines for conversion of binary strings to int and int to binary string. I realize this is reinvetning the ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
March 2, 2014
🌐
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 ?
🌐
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
🌐
Blogger
naimcprogram.blogspot.com › 2016 › 02 › c-program-to-convert-text-string-to.html
C Program to Convert Text String to Binary - NAIMCPROGRAM
NAIMCPROGRAM Binary Convert String Text C Program to Convert Text String to Binary · Binary Convert String Text · 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"); } Share on FacebookTweet on TwitterPlus on Google+ « Prev Question ·
Find elsewhere
🌐
Forgetcode
forgetcode.com › c › 1852-decimal-to-binary-conversion-of-a-string
Decimal to binary Conversion of a String in C - Forget Code
Algorithms13 Applications5 Arithmetic Operations2 Array8 Basics27 Compiler Design1 Control Statements4 Conversion Functions1 Data Structures12 Data Type1 Date Functions1 File36 Keywords1 Loops1 Math Functions30 Math Snippets43 Memory Management3 Misc4 Networking4 Operators6 Pointers17 String Functions30 String Snippets29 System Software10 Utility Snippets1 ... #include <stdio.h> #include <stdlib.h> char *decimal_to_binary(int); main() { int n, c, k; char *pointer; printf("Enter an integer in decimal number system\n"); scanf("%d",&n); pointer = decimal_to_binary(n); printf("Binary string of %d
🌐
C For Dummies
c-for-dummies.com › blog
From String to Binary | C For Dummies Blog
April 14, 2018 - The returned int value is initialized to zero, which means the processing needs only to set bits: When a '1' is encountered in the string, a bit is set; when a '0' is encountered, the bit is skipped or left at its current, zero value. The bitwise OR operator, | (the pipe), sets the bits. I wrote a post on this topic a while back.
🌐
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
Top answer
1 of 3
7

It makes sense for the two functions to be symmetrical - ie that you can call them in turn to swap between integer and string representations. So I would make binstr2int produce an unsigned long of full range returned through a parameter and have the function return the status (0/-1):

int binstr2int(const char *s, unsigned long &num);

Note that s can be const.

In int2binstr I think the characters should be moved to the beginning of the string - this is what all other C string functions do (or at least I'm ignorant of any that do not). Also, your code is a bit awkward in that it treats 0 separately from all other numbers. This is a case where a do {...} while loop makes sense as it can handle the zero case as any other number and test for zero once it has done it:

char* int2binstr(unsigned long num, char *s, size_t size)
{
    long len = (long) size - 1;
    do {
        if (len <= 0) {
            errno = ERANGE;
            return NULL;
        }
        s[--len] = (num & 1) ? '1' : '0';
    } while ((num >>= 1) != 0);

    long n = (long) size - len - 1;
    memmove(s, s + len, n);
    s[n] = '\0';
    return s;
}

Here you can see that the tests for a short input string and for num == 0 are handled naturally. Also I moved the string into place after creating it.

2 of 3
4

In int2binstr the comment says, "NULL returned on error check errno" but you don't return NULL on error: instead you return a pointer to an empty string.

Also, I find it unusual that int2binstr writes its result at the end of the passed-in buffer, instead of at the beginning.

Also, why use long in the first function but unsigned long in the second function.

🌐
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.
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.

🌐
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.:
🌐
Stack Overflow
stackoverflow.com › questions › 73425120 › how-do-i-convert-a-really-long-string-to-binary-in-c
How do I convert a really long string to binary in C? - Stack Overflow
August 20, 2022 - To instead convert the string from decimal form into a binary string, allocate sufficient buffer (about log10(2) times string length) and instead of printing above, save to the buffer.
🌐
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.