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