This little C program converts a char variable to its binary representation.
#include <stdio.h>
#include <string.h>
/*
* This function returns the correct order.
*/
void
char_to_bin_v1(char c)
{
int i, bin;
char ch = c;
printf("ch's char value: %c\n", ch);
printf("ch's decimal value: %d\n", ch);
printf("ch's binary value: ");
for (i = 0; i < 8; i++) {
bin = ((ch << i) & 0x80) ? 1 : 0;
printf("%d", bin);
}
/* printf("\n"); */
}
int
main()
{
char msg[1024] = "Hello, world!";
char letter;
int i, n = 0;
printf("char to binary - version 1:\n");
for (i = 0; i < strlen(msg); i++) {
letter = msg[i];
char_to_bin_v1(letter);
printf(" ");
n++;
/* A maximum number of 14 character's per line */
if (n == 14) {
printf("\n");
n = 0;
}
}
printf("\n");
return(0);
}