[英]C: Compresing DNA sequence into binary
嗨,我正在嘗試找出如何獲得將 DNA 代碼轉換為二進制位的函數,需要使它看起來像這樣:ACGTT -> XXXXXX11 11100100 從右到左為 A=0 C=1 G=2 T=3 . 現在我想按字符來做,然后將它移出功能>>2,但我無法弄清楚函數本身......我像這樣試過,這樣它返回NULL。
char CompressChar(char c){
char temp[8]="XXXXXXXX";
if (c=='A'){
temp[7] = '0';
temp[6] = '0';
}
if (c=='C'){
temp[7]='1';
temp[6]='0';
}
if(c=='G'){
temp[7]='0';
temp[6]='1';
}
if(c=='T'){
temp[7]='1';
temp[6]='1';
}
return temp;
}
我認為您希望每個字母(它們被稱為核苷酸 iirc?)代表 2 個二進制數字。
首先, char temp[8]="XXXXXXXX";
沒有意義,因為 C 中的字符串以空結尾,並且您沒有為空終止符分配空間,應該是[8+1]
。 你想要 16 位,而不是 8 位。
您的函數返回一個不正確的char
,您需要返回整個數組。 這必須通過一個參數來完成,因為你不能在 C 中返回數組。你不能返回一個指向本地數據的指針,所以最好將分配留給調用者。 無論如何...划傷那個功能。
此外,將其轉換為“二進制字符串”沒有多大意義。 最好將其轉換為二進制數,然后根據需要將該數字轉換為字符串。
轉換,包括“倒序”,然后可以這樣完成:
uint16_t dna_to_bin (const char* str)
{
uint16_t result = 0;
size_t i;
for(i=0; i<16; i+=2) // loop over bits in the resulting binary number
{
typedef enum // local enum just for readability
{
A = 0,
C = 1,
G = 2,
T = 3,
} dna_t;
dna_t type=0; // default is 0 if nothing to decode
if(*str != '\0') // keep decoding string until reaching the end
{
switch(*str)
{
case 'A': type = A; break;
case 'C': type = C; break;
case 'G': type = G; break;
case 'T': type = T; break;
}
str++;
}
result |= (uint16_t)type << i; // store data at correct position in the result
}
return result;
}
完整示例包括一個打印二進制並丟棄下面前導零的函數。 如果你想用 X 替換前導零,修改應該很簡單。
#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdbool.h>
uint16_t dna_to_bin (const char* str)
{
uint16_t result = 0;
size_t i;
for(i=0; i<16; i+=2)
{
typedef enum
{
A = 0,
C = 1,
G = 2,
T = 3,
} dna_t;
dna_t type=0;
if(*str != '\0')
{
switch(*str)
{
case 'A': type = A; break;
case 'C': type = C; break;
case 'G': type = G; break;
case 'T': type = T; break;
}
str++;
}
result |= (uint16_t)type << i;
}
return result;
}
void print_bin (uint16_t bin)
{
bool remove_zeroes = true;
for(size_t i=0; i<16; i++)
{
uint16_t mask = 1u << (16-1-i);
uint16_t bit = bin & mask;
if(bit == 0)
{
if(!remove_zeroes)
{
printf("0");
}
}
else
{
remove_zeroes = false;
printf("1");
}
}
}
int main (void)
{
const char STR_DNA[] = "ACGTT";
uint16_t bin = dna_to_bin(STR_DNA);
puts(STR_DNA);
printf("Hex: %.4"PRIX16 "\n", bin);
printf("Bin: ");
print_bin(bin);
return (0);
}
輸出:
ACGTT
Hex: 03E4
Bin: 1111100100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.