Skip to content

Instantly share code, notes, and snippets.

@nikp123
Created July 17, 2018 09:57
Show Gist options
  • Save nikp123/aea4fa89fc05083e7e34f08593d94ad5 to your computer and use it in GitHub Desktop.
Save nikp123/aea4fa89fc05083e7e34f08593d94ad5 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
if(argc<2) {
printf("Usage: %s outputfile\n", argv[0]);
return 1;
}
FILE *output = fopen(argv[1], "wb");
if(!output) {
fprintf(stderr, "Cannot open file %s for writing\n");
return 2;
}
int bitsToWrite = 0;
char *memory = malloc(sizeof(char)*1+1);
memory[0] = 0x00;
static struct termios oldt,newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
char c, counter = 0, oldsize=1;
while((c=getchar())!='\n') {
if(c=='1'||c=='0') {
putchar(c);
memory[counter/8] |= ((c-'0'? 1 : 0)<<(7-counter%8));
counter++;
if(counter/8==oldsize) {
oldsize++;
char *backup = realloc(memory, sizeof(char)*oldsize+1);
if(backup==NULL) {
fprintf(stderr, "Not enough memory for operation!\n");
return 3;
}
memory=backup;
}
if(counter%8==0) putchar(' ');
} else if(c==8||c==127) {
putchar(8);
putchar(' ');
putchar(8);
counter--;
if(counter/8+1<oldsize) {
putchar(8);
oldsize--;
char *backup = realloc(memory, sizeof(char)*oldsize+1);
if(backup==NULL) {
fprintf(stderr, "Not enough memory for operation!\n");
return 3;
}
memory=backup;
}
memory[counter/8] &= ~(1<<(7-counter%8));
}
}
printf("\nSaving to file %s\n", argv[1]);
fwrite(memory, sizeof(char), counter%8==0? oldsize-1 : oldsize, output);
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fclose(output);
free(memory);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment