Search code examples
c#dna-sequence

encoding binary to DNA sequence inC#


I would like to encode binary sequence to DNA sequence by truth table : 00=A 01=C 10=G 11=T For example:11000110=``TACGBy using C#, My issue, is the DNA sequence is not correctly converted. Does someone can help me PLEASE ?

the code i write is this :

 string ds = Convert.ToString(result , 2);

                       ;
                       int l = ds.Length;
                       for (int dd= 0; dd < l; dd = dd + 2)
                       {

                           if (ds.Contains("00"))
                           {
                               ds = ds.Replace("00", "A");

                           }
                           if (ds.Contains("01"))
                           {
                               ds = ds.Replace("01", "C");

                           }
                            if (ds.Contains("10"))
                           {
                               ds = ds.Replace("10", "G");
                           }
                           else
                           {
                           ds = ds.Replace("11", "T");
                           }
                       }
                       listBox7.Items.Add(ds);

Solution

  • Here is my proposal. In fact, there are thousands of possible solutions.

        string binary = "011001010101000100101";
        var codes = new Dictionary<string, string> {
            {"00", "A"},
            {"01", "C"},
            {"10", "G"},
            {"11", "T"}
        };
    
        StringBuilder builder = new StringBuilder();
    
        for(int i = 0; i + 1 < binary.Length; i = i + 2) {
            var localCode = string.Format("{0}{1}", binary[i], binary[i+1]);
            string buffer;
            var output = codes.TryGetValue(localCode, out buffer) ? buffer : string.Empty;
            builder.Append(output);
        }
    
        string result = builder.ToString();