Every character has ASCII Code, ' A ' has ASCII Code 65 ( Decimal ), and 41 ( Hex ). String is array of characters. To convert string to binary code, we must to convert every characters of string to binary code. If we convert character of string one by one, it will take a lot of time.So, this time we will make a C Program which it will convert our string to binary code. There is the simple algoritm in pseudo code..
C Program Algoritm in Pseudo Code
Simple algoritm :// Pseudo code convert string to binary codePseudo code above couldn't be compiled by the C compiler. We must to convert it to C syntax, So we could compile it.
Declaration :
structure bits {
unsigned bit0:1
...
unsigned bit7:1
}
union {
unsigned char character
structure byte bits
} ascii
Process :
print ( " Plain text : " )
while (( scan ( ascii.character ) != EOF )) {
write ( int, int, int, int, int, int, int ,int ){
ascii.byte.bit7, ... ascii.byte.bit0
}
}
// Electronicsbot - String to Binary code
C Source Code to Convert String to Binary Code
From the pseudo code above, we can get source code below.// C Program Convert String to Binary CodeNote : Statment sloping modified from Real Algoritm ( Pseudo Code Above ).
#include <stdio.h>
void main() {
struct bits {
unsigned bit0:1;
unsigned bit1:1;
unsigned bit2:1;
unsigned bit3:1;
unsigned bit4:1;
unsigned bit5:1;
unsigned bit6:1;
unsigned bit7:1;
};
union {
unsigned char character;
struct bits byte;
} ascii ;
// Statment sloping modified from Real Algoritm
printf("\n*** Program Convert String to Binary Code ***\n");
printf("************* by Electronics bot *************\n");
while( getchar()!=EOF ){
printf("Plain Text : ");
while( (ascii.character = getchar() ) != '\n' ){
printf("%d%d%d%d%d%d%d%d ",
ascii.byte.bit7,
ascii.byte.bit6,
ascii.byte.bit5,
ascii.byte.bit4,
ascii.byte.bit3,
ascii.byte.bit2,
ascii.byte.bit1,
ascii.byte.bit0
);
}
putchar('\n');
}
}
You could compile source code above and compile it !
Belum ada tanggapan untuk "How to convert string to binary code using C program"
Post a Comment