2010-08-27 134 views
34

在c#中,我将byte转换为binary,实际答案为00111111,但给出的结果为111111。现在我真的需要在前面显示2个0。谁能告诉我如何做到这一点?将字节转换为c中的二进制字符串#

我使用:

Convert.ToString(byteArray[20],2) 

和字节值是63

+0

相似,但相反:http://stackoverflow.com/questions/72176/using-c-what-is-the-most-efficient-method-of-转换一个字符串包含bi bi – 2010-08-27 19:33:17

回答

38

只要改变你的代码:

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

此方法将始终使字符串与8位数的权利?所以如果我会得到不同的值,例如10001111,这不会在前面添加新的0 – IanCian 2010-08-27 08:59:31

+3

@IanCian是正确的,不管总是有8位数字,所以如果你提供所有的数字,PadLeft将不会做任何事情,除非你不要,它会用0来填充左边的空格。 – Kelsey 2010-08-27 15:07:46

+0

你是对的 - 我的建议是不正确的。我没有测试它。 – Zach 2010-08-28 23:59:24

0

试试这个:

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

如果我理解正确,你有20诉你想转换的线索,所以这只是你写的帽子的简单改变。

要更改单个字节至8字符的字符串:Convert.ToString(x, 2).PadLeft(8, '0')

要更改全排列:

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 

要改变您的字节数组单个串,用空格隔开的字节:

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 

如果字节排序不正确使用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

试试这个

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(); 
    }