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
Coleton
  • 19
  • 1
  • 3
  • 1
    `scanf("%s",&c);` should be `scanf("%s",c);` – Jayesh Bhoi Sep 29 '14 at 04: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' ? – Martin James Sep 29 '14 at 04:24
  • Yes, I want to change the ASCII values into a visual of Binary, such as 1's and 0's. – Coleton Sep 29 '14 at 04:25

1 Answers1

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;
}
Anbu.Sankar
  • 1,326
  • 8
  • 15