0

I'm trying to convert the ASCII values of each letter, into Binary but I'm not sure how to grab the decimal values and convert them. Here's the code that prints out a word with their ASCII values to the right

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


int main (void) {

   char c[20];
   printf("Enter a word: ");
   scanf("%s",&c);

   int i;
   char *str = c;
   int length = strlen(str);

   for (i = 0; i < length; i++) {
      printf("%c = %d \n", str[i] , str[i]);
   }
   return 0;
}

Example output:

Enter a word: Program
P = 80
r = 114
o = 111
g = 103
r = 114
a = 97
m = 109
3
  • 1
    scanf("%s",&c); should be scanf("%s",c); Commented Sep 29, 2014 at 4:24
  • You should be aware that they are already binary. They have to be because your processor can only handle binary instruction code and data. I'm guessing that you mean a textual representation of the binary, eg '10100110' ? Commented Sep 29, 2014 at 4:24
  • Yes, I want to change the ASCII values into a visual of Binary, such as 1's and 0's. Commented Sep 29, 2014 at 4:25

1 Answer 1

3

Try this one...Pgm for Binary printing..

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


int main (void) {

char c[20];
printf("Enter a word: ");
scanf("%s",c);//here no need &
    int j;
int i;
char *str = c;
int length = strlen(str);

for (i = 0; i < length; i++)
 {


   for(j=7;j>=0;j--)//for binary print; for char j=7, for int j=31
    {
    if((str[i]>>j&1)==1)
    printf("1");
    else
    printf("0");
    }


  printf("\n%c = %d \n", str[i] , str[i]);
}
return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note: that hand-rolled 7 should be based on CHAR_BIT. example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.