2013-06-24 2 views
0

Je veux concaténer certains bits en un seul. J'ai cette méthode:Concat bits en une chaîne

public BitArray Encode(string source) 
{ 
    List<bool> encodedSource = new List<bool>(); 

    for (int i = 0; i < source.Length; i++) 
    { 
     List<bool> encodedSymbol = this.Root.Traverse(source[i], new List<bool>()); 
     encodedSource.AddRange(encodedSymbol); 
    } 

    BitArray bits = new BitArray(encodedSource.ToArray()); 

    return bits; 
} 

Il me revient 0/1 bits binaires, maintenant j'ai ce code pour me montrer la sortie:

foreach (bool bit in encoded) 
{ 
    MessageBox.Show((bit ? 1 : 0) + ""); 
} 

Maintenant, je suis juste montrant un MessageBox pour chaque bit , mais comment puis-je simplement concaténer tous les bits dans un MessageBox, c'est peut-être une question idiote mais je ne peux pas m'en passer la tête.

Répondre

5
var bitString = string.Concat(encoded.Select(bit => bit ? "1" : "0")) 
+0

Merci cela a fait l'affaire! – user2022298

1

utilisation StringBuilder

StringBuilder tmp = new StringBuilder(encoded.Count) 
foreach (bool bit in encoded) 
{ 
    tmp.Append(bit ?"1": "0")); 
} 
MessageBox.Show(tmp.ToString()); 
+0

Testé cela et fonctionne aussi, merci pour l'effo rt! – user2022298

+0

De rien) –

1

Ce visualise ce que vous devez faire:

Il va essentiellement creux toutes les entrées et en ajoutant soit un « 1 » ou « 0 » à la liste, en fonction de l'entrée.

public static string ConcatList(List<bool> list) 
    { 
     StringBuilder builder = new StringBuilder(); 
     foreach (bool b in list) 
     { 
      builder.Append(b == true ? "1" : "0"; 
     } 
     return builder.ToString(); 
    } 
0

Ma suggestion:

string bitString = string.Empty; 
foreach (bool bit in encodedSource) 
{ 
    bitString = string.Concat(bitString, (bit ? "1" : "0")); 
} 
+1

Problème potentiel de performance avec toutes les concaves de cordes. Les autres réponses avec 'StringBuilder' l'évitent. –

1

Voici une méthode d'extension sur BitArray qui devrait faire l'affaire:

public static class BitArrayExtensions 
{ 
    public static string ToBitString(this BitArray encoded) 
    { 
     if (encoded == null) 
     { 
      return string.Empty; 
     } 

     var sb = new StringBuilder(encoded.Count); 

     foreach (bool bit in encoded) 
     { 
      sb.Append(bit ? "1" : "0"); 
     } 

     return sb.ToString(); 
    } 
} 

utilisation dans votre code en tant que tel:

MessageBox.Show(encoded.ToBitString()); 
Questions connexes