0

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?

3 Answers 3

4

You declared b as a array of struct so if you print the value of b it will give you the base address of array.
Use loop to print the array values.
You are using w to get the binary value but the input is in wordd[] did you copy the value ?

Sign up to request clarification or add additional context in comments.

Comments

0

You need to print the values of the individual entries in the array rather than the value of b (which will just print the address of b as b standalone represents the pointer)

Comments

0

You haven't initialized w. Bear in mind that fgets() stores the new-line character within the string, so it's better to remove it, before proceeding. Do something like:

int i;
for (i=0; i<size_word; i++) {
    if (wordd[i] == '\0') {
       wordd[i] = 0;
       break;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.