Created
January 24, 2019 15:03
-
-
Save mythosil/ae84f735259f31c52d11402fd18b3b4f to your computer and use it in GitHub Desktop.
DNA complement (A<>T, G<>C, N<>N) with only bit operations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
char dna_complement(char dna) | |
{ | |
dna ^= 0x15; | |
dna ^= (dna & 0x02) << 3; | |
dna ^= (dna & 0x02) >> 1; | |
dna ^= (dna & 0x08) >> 1; | |
return dna; | |
} | |
int64_t dna_complement_int64(int64_t dnas) | |
{ | |
dnas ^= 0x1515151515151515; | |
dnas ^= (dnas & 0x0202020202020202) << 3; | |
dnas ^= (dnas & 0x0202020202020202) >> 1; | |
dnas ^= (dnas & 0x0808080808080808) >> 1; | |
return dnas; | |
} | |
int main() | |
{ | |
printf("%c\n", dna_complement('A')); // => T | |
printf("%c\n", dna_complement('T')); // => A | |
printf("%c\n", dna_complement('G')); // => C | |
printf("%c\n", dna_complement('C')); // => G | |
printf("%c\n", dna_complement('N')); // => N | |
char *dnas = "ATGCNNNN"; | |
int64_t dnas_comp = dna_complement_int64(*((int64_t *) dnas)); | |
char *s = (char *) &dnas_comp; | |
printf("%c%c%c%c%c%c%c%c\n", // => TACGNNNN | |
s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment