01010011011000010111100100100000010010010111010000100000
01101001011011100010000001000010011010010110111001100001
011100100111100100001010
The bits above represent the ASCII code values for the text, “Say It in Binary.” That’s because I ran that text through this week’s program, which is designed to take up to 63 characters of text and spew out the binary values of the text’s characters (the ASCII codes).
Why would anyone do this?
I needed to place some binary text into an illustration for a project I’m working on. Rather than type 1010101 over and over again, I decided to code a quick program in C. That program would take text and convert it into a long, binary string. That way I could place an Easter Egg of sorts into the illustration.
Easter Eggs are nothing new in my books. The original C For Dummies featured one, which is discussed on this web page. Now I’ve created another one, by using the sample code shown below.
#include <stdio.h>
char *binbin(int n);
int main()
{
char input[64];
int x = 0;
printf("Type the text: ");
fgets(input,63,stdin);
while(input[x] != '\0')
printf("%s",binbin(input[x++]));
putchar('\n');
return(0);
}
char *binbin(int n)
{
static char bin[9];
int x;
for(x=0;x<8;x++)
{
bin[x] = n & 0x80 ? '1' : '0';
n <<= 1;
}
bin[x] = '\0';
return(bin);
}
This code uses my binbin() function, which translates an int value into an 8-bit string of binary digits. The main() function reads a string at Line 11. A while loop then processes the string one character at a time, using the binbin() function on that individual character (Lines 13 and 14).
Because ASCII uses only 7 bits, the code could be modified to display only those 7 bits. If you note in the output (above), each initial bit (the 8th bit) is always zero. That modification involves a change to the binbin() function, which you can try on your own as a fun little exercise.