c - Convert Ascii to Binary -
i writing program need convert ascii characters binary , count. have gotten code working printing additional information , not correct binary. below code output given set of characters. assistance appreciated!
#include <stdio.h> #include <stdlib.h> void binaryprinter(int digend, int value, int * noofones); void print(char c); int chartoint(char c) { return (int) c; } int main() { char value; int result = 1; while(result != eof) { result = scanf("%c", &value); if(result != eof) { print(value); } } } void binaryprinter(int digend, int value, int * noofones) { if(value & 1) { (*noofones) = (*noofones) + 1; value = value >> 1; digend--; printf("1"); } else { value = value >> 1; digend--; printf("0"); } if(digend == 0) return; else binaryprinter(digend, value, noofones); } void print(char c) { int count = 0; printf("the character %c =", c); binaryprinter(8, chartoint(c), &count); printf(" 1's = %d\n", count); }
here's pair of functions:
void printcharasbinary(char c) { int i; for(i = 0; < 8; i++){ printf("%d", (c >> i) & 0x1); } } void printstringasbinary(char* s){ for(; *s; s++){ printcharasbinary(*s); printf(" "); } printf("\n"); }
you can see them in action here: http://ideone.com/3mevbe. work masking out single bit of each character , printing 1 @ time.
Comments
Post a Comment