This is another version of a char variable to binary program.
#include <stdio.h>
#include <string.h>
/*
* When translating from char to binary we are using this map:
*
* Dec. Bin. Hex.
* 1 <=> 00000001 <=> 0x01 => 1*2^0
* 2 <=> 00000010 <=> 0x02 => 1*2^1
* 4 <=> 00000100 <=> 0x04 => 1*2^2
* 8 <=> 00001000 <=> 0x08 => 1*2^3
* 16 <=> 00010000 <=> 0x10 => 1*2^4
* 32 <=> 00100000 <=> 0x20 => 1*2^5
* 64 <=> 01000000 <=> 0x40 => 1*2^6
* 128 <=> 10000000 <=> 0x80 => 1*2^7
*/
/*
* This function returns the correct order as well.
*/
void
char_to_bin_v2(char c)
{
int i, bin[8];
char ch = c;
bin[0] = (ch & 0x01) ? 1 : 0;
bin[1] = (ch & 0x02) ? 1 : 0;
bin[2] = (ch & 0x04) ? 1 : 0;
bin[3] = (ch & 0x08) ? 1 : 0;
bin[4] = (ch & 0x10) ? 1 : 0;
bin[5] = (ch & 0x20) ? 1 : 0;
bin[6] = (ch & 0x40) ? 1 : 0;
bin[7] = (ch & 0x80) ? 1 : 0;
for(i = 0; i < 8; i++)
printf(%d; bin[i]);
}
int
main(int argc, char *argv[])
{
char msg[1024] = "Hello, world!";
char letter;
int i, n = 0;
printf("Char to binary - Version 2:\n");
for (i = 0; i < strlen(msg); i++) {
letter = msg[i];
char_to_bin_v2(letter);
printf(" ");
n++;
/* A maximum number of 14 character's per line */
if (n == 14) {
printf("\n");
n = 0;
}
}
printf("\n");
return(0);
}