Skip to content

Instantly share code, notes, and snippets.

@agdiaz
Last active February 6, 2018 02:03
Show Gist options
  • Save agdiaz/d1aa402810c219acd773b6f2ebd9f6f5 to your computer and use it in GitHub Desktop.
Save agdiaz/d1aa402810c219acd773b6f2ebd9f6f5 to your computer and use it in GitHub Desktop.
Reads a binary file and write a new one with the sequence as a string
// Compile: gcc -o bit2dna bit_dna.c
// Libraries
#include <stdio.h>
#include <string.h>
// Declare constants
#define A 0 // 00
#define C 1 // 01
#define G 2 // 10
#define T 3 // 11
#define BYTES_PER_BATCH 1
// Declare headers and structs
char translate(unsigned int base);
struct NucleotidWord {
unsigned int base0: 2;
unsigned int base1: 2;
unsigned int base2: 2;
unsigned int base3: 2;
};
// Main function
// It receives as argument the path and read the dna sequence
// ./dna_bit path/to/read.dna path/to/write.seq
int main(int argc, char** params) {
FILE *read_ptr;
FILE *write_ptr;
char* pathToReadFile = params[1];
char* pathToWriteFile = params[2];
printf("Welcome to Bit2DNA version 0.0.1\n");
printf("Input path: %s \n", pathToReadFile);
read_ptr = fopen(pathToReadFile, "rb");
write_ptr = fopen(pathToWriteFile, "w");
// Declare buffer variables:
struct NucleotidWord buffer;
char writeBuffer;
unsigned int bytesRead = 0;
while (fread(&buffer, 1, 1, read_ptr)) {
writeBuffer = translate(buffer.base3);
fwrite(&writeBuffer, sizeof(char), 1, write_ptr);
writeBuffer = translate(buffer.base2);
fwrite(&writeBuffer, sizeof(char), 1, write_ptr);
writeBuffer = translate(buffer.base1);
fwrite(&writeBuffer, sizeof(char), 1, write_ptr);
writeBuffer = translate(buffer.base0);
fwrite(&writeBuffer, sizeof(char), 1, write_ptr);
bytesRead++;
printf("\n");
}
writeBuffer = '\n';
fwrite(&writeBuffer, sizeof(char), 1, write_ptr);
// Closes the file and exit successfuly
fclose(read_ptr);
fclose(write_ptr);
// Print statistics
printf("Total bytes read: %d\n", bytesRead);
printf("File read from: %s\n", pathToReadFile);
printf("File written in: %s\n", pathToWriteFile);
return 0;
}
char translate(unsigned int base) {
printf("Translating %d\n", (int)base);
char nucleotid;
if (base == A) {
nucleotid = 'A';
} else if (base == C) {
nucleotid = 'C';
} else if (base == G) {
nucleotid = 'G';
} else {
nucleotid = 'T';
}
return nucleotid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment