2010-08-27 18 views
34

In C# sto convertendo uno byte in binary, la risposta effettiva è 00111111 ma il risultato dato è 111111. Ora ho davvero bisogno di visualizzare anche i 2 0 davanti. Qualcuno può dirmi come farlo?Conversione di un byte in una stringa binaria in C#

sto usando:

Convert.ToString(byteArray[20],2) 

e il valore di byte è 63

+0

simile, ma in senso inverso: http://stackoverflow.com/questions/72176/using-c-what-is-the-most-efficient-method-of- converting-a-string-containing-bi –

risposta

38

Basta modificare il codice per:

string yourByteString = Convert.ToString(byteArray[20], 2).PadLeft(8, '0'); 
// produces "00111111" 
+0

questo metodo creerà sempre la stringa con 8 cifre giusto? quindi se otterrò un valore diverso per esempio 10001111 questo non aggiungerà nuovi 0 davanti – IanCian

+3

@IanCian corretto, non importa cosa ci saranno sempre 8 cifre quindi se li fornite tutti, il 'PadLeft' non farà nient'altro se non voi no, riempirà lo spazio sinistro a sinistra con 0s. – Kelsey

+0

Hai ragione - il mio suggerimento non era giusto. Non l'ho provato – Zach

0

Provate questo:

public static String convert(byte b) 
{ 
    StringBuilder str = new StringBuilder(8); 
      int[] bl = new int[8]; 

    for (int i = 0; i < bl.Length; i++) 
    {    
     bl[bl.Length - 1 - i] = ((b & (1 << i)) != 0) ? 1 : 0; 
    } 

    foreach (int num in bl) str.Append(num); 

    return str.ToString(); 
} 
19

Se Ho capito bene, hai 20 v alori che vuoi convertire, quindi è solo un semplice cambiamento di cappello che hai scritto.

Per cambiare singolo byte per stringa 8 char: Convert.ToString(x, 2).PadLeft(8, '0')

Per cambiare allineamento completo:

byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 }; 
string[] b = a.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')).ToArray(); 
// Returns array: 
// 00000010 
// 00010100 
// 11001000 
// 11111111 
// 01100100 
// 00001010 
// 00000001 

Per modificare la matrice di byte in un'unica stringa, con byte separati da spazi:

byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 }; 
string s = string.Join(" ", 
    a.Select(x => Convert.ToString(x, 2).PadLeft(8, '0'))); 
// Returns: 00000001 00001010 01100100 11111111 11001000 00010100 00000010 

se l'ordine dei byte non è corretto utilizzare IEnumerable.Reverse():

byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 }; 
string s = string.Join(" ", 
    a.Reverse().Select(x => Convert.ToString(x, 2).PadLeft(8, '0'))); 
// Returns: 00000010 00010100 11001000 11111111 01100100 00001010 00000001 
2

provare questo

public static string ByteArrayToString(byte[] ba) 
    { 
     StringBuilder hex = new StringBuilder(ba.Length * 2); 
     foreach (byte b in ba) 
      hex.AppendFormat("{0:x2}", b); 
     return hex.ToString(); 
    } 
Problemi correlati