Hello all!Im trying to write a program that accepts a string from users and then converts each character in the string to its corresponding 8-bit binary code and store it for further manipulation on obtained bit. I have the following code but it is not executing as expected :

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

int xstrlen (char *s) //for later use
{
int length = 0 ;
while ( *s != '\0' )
{
length++ ;
s++ ;
}
return ( length ) ;
}

char* showbits(int n) //to print binary equivalent
{
int i, k, andmask ;

char* p=(char *)malloc(9); //8 bytes for 8 bit binary and 1byte for null character at end
for ( i = 7 ; i >= 0 ; i-- )
{
    andmask = 1 << i ;
    k = n & andmask ;

    if(k==0)
    {
       strcat(p,"0");
    }

    else
    {
       strcat(p,"1");
    }
}
*ptr='\0'; //dont know if its correct
return p;
}


void msg2bits(char *msg)
{

    char* bits;
    int x;
    int i=0;


   while(*msg!='\0')
   {
       x=(int)msg[i];
       bits=showbits(x);

       puts(bits);
       msg++;
       i++;
    }
}


int main(int argc,char *argv[])
{
    char *msg="ABCD";

    msg2bits(msg);
    getch();
    return 0;
}

finally solved the problem. here is the modified code:-

char* showbits(int n)
{
int i, k, andmask ;

char* p=malloc(9*sizeof(char));
*p='\0';
for ( i = 7 ; i >= 0 ; i-- )
{
    andmask = 1 << i ;
    k = n & andmask ;

    if(k==0)
    {
       strcat(p,"0");
    }

    else
    {
       strcat(p,"1");
    }
}

return p;
}


void msg2bits(char *msg)
{
    char *bits=malloc(9*sizeof(char));
    int x;

   while(*msg!='\0')
   {
       x=(int)msg[0];
       bits=showbits(x);
       puts(bits);
       msg++;
    }
}

Well done. However, you have two glaring errors in the modified code. See if you can find them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.