I need to write a program that reads in a character string and prints out the binary ASCII code for that string. I do not know the length of the string, and I need to implement data structures somewhere in the program. The source code I have written is:
#include <stdio.h>
int dec_to_binary(int c, int d);
//initialize data structure for binary value
struct binary{
int value;
};
struct word{
int w_value;
};
int main(){
char wordd[256];
printf("Input a string of characters (no spaces): \n");
//scanf("%s", w);
fgets(wordd, sizeof(wordd), stdin);
printf("You typed: %s", wordd);
int size_word = sizeof(wordd);
struct word w[size_word]; //stores character string
struct binary b[size_word]; //initizalize corresponding binary array for char string inputted by user
int i = 0;
int char_int = 0;
for (i = 0; i < size_word; i++)
{
char_int = w[i].w_value;
b[i].value = dec_to_binary(char_int, size_word); //stores binary value in binary struct array
}
printf("The binary ASCII code for this string is: %d", b);
return 0;
}
int dec_to_binary(int c, int d)
{
int i = 0;
for(i = d; i >= 0; i--){
if((c & (1 << i)) != 0){
return 1;
}else{
return 0;
}
}
}
When I compile it I don't get any errors, but my output is incorrect:
Input a string of characters (no spaces):
eli
You typed: eli
The binary ASCII code for this string is: 2421936
I get the returned value 2421936 no matter what input I try. Any ideas as to where I'm going wrong?