Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //This program is by Usmar A Padow (amigojapan) usmpadow@gmail.com
- //converts ascii to binary and binary to ascii in C
- //source https://www.youtube.com/watch?v=XykJzVbrf3s
- #define MASK0 0x01
- #define MASK1 0x02
- #define MASK2 0x04
- #define MASK3 0x08
- #define MASK4 0x10
- #define MASK5 0x20
- #define MASK6 0x40
- #define MASK7 0x80
- unsigned char AtoB(char *ASCII) {//returns a unsigned char that is the binary value of the ascii sent
- //GeDaMo: amigojapan: well, those masks are a bit pointless, MASK0 is 1 << 0, MASK1 is 1 << 1 etc.
- //GeDaMo: amigojapan: also, |= exists so you can write a |= b instead of a = a | b
- unsigned char result;//this will contain the binary result
- if(ASCII[7]=='1') result = result | MASK0;
- if(ASCII[6]=='1') result = result | MASK1;
- if(ASCII[5]=='1') result = result | MASK2;
- if(ASCII[4]=='1') result = result | MASK3;
- if(ASCII[3]=='1') result = result | MASK4;
- if(ASCII[2]=='1') result = result | MASK5;
- if(ASCII[1]=='1') result = result | MASK6;
- if(ASCII[0]=='1') result = result | MASK7;
- return result;
- }
- #include<string.h>
- #include<stdio.h>
- unsigned char AtoB2(char *ASCII) {//returns a unsigned char that is the binary value of the ascii sent
- //GeDaMo: amigojapan: well, those masks are a bit pointless, MASK0 is 1 << 0, MASK1 is 1 << 1 etc.
- //GeDaMo: amigojapan: also, |= exists so you can write a |= b instead of a = a | b
- unsigned char result;//this will contain the binary result
- result=0;
- //printf("strlen(ASCII):%lu, ",strlen(ASCII));
- //if(strlen(ASCII)>sizeof(result)) return result;//exit gracefully if the ASCII is too long for the architecture we are on
- int up, down;
- for(up=strlen(ASCII)-1,down=0;down < strlen(ASCII);up--,down++) {
- int mask;
- mask=1 << down;
- if(ASCII[up]=='1') result |= mask;
- }
- return result;
- }
- //binary conversion function Binary to Ascii by GeDaMo
- void BtoA(unsigned char ch, char *b) {
- int mask = 0x80;
- int i;
- for (i = 0; i < 8; ++i) {
- b[i] = ch & mask ? '1' : '0';
- mask >>= 1;
- }
- b[i] = '\0';
- }
- int main(void) {//test program to test both functions
- //char ASCII[9]="10101010";
- char ASCII[9]="1001";
- char ASCII2[9];
- unsigned char BINARY;
- BINARY = AtoB2(ASCII);
- BtoA(BINARY,ASCII2);
- printf("%s",ASCII2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement