0

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;
}

Edited by prerit

2
Contributors
2
Replies
11
Views
3 Years
Discussion Span
Last Post by deceptikon
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++;
    }
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.