2016-06-27 42 views
1

我在c#中編寫代碼。 我需要讀取字符串的字符串而不進行轉換。C#將字節數組讀取爲字符串

字節:68 字符串:44

我希望能夠將其轉換通過代碼


我想通了

#region "Grab Bytes Function" 
private string grabBytes(byte[] buffer) 
{ 
    byte[] bytes = buffer; 
    string output = string.Empty; 
    foreach (byte item in bytes) 
    { 
      output += Convert.ToString(item, 16).ToUpper().PadLeft(2, '0'); 
    } 
    return output; 
} 
#endregion 
#region "Grab String Function" 
private string grabString(byte[] buffer) 
{ 
    byte[] bytes = buffer; 
    string output = string.Empty; 
    foreach (byte item in bytes) 
    { 
     for (int i = 0; i < 255; i++) 
     { 
      if (grabBytes(new byte[] { item }) == grabBytes(new byte[] { byte.Parse(i.ToString()) })) 
       output += item + "."; 
     } 
    } 
    string output1 = output.Remove(output.Count() - 1, 1); 
    if (output1 != "0.0.0.0") 
     return output1; 
    else 
     return ""; 
} 
#endregion 
+0

是存儲在字符串或字節[]中的字節。如果是這種情況,只需要將其轉換爲:'var str = System.Text.Encoding.Default.GetString(result);'。如果它在字符串中,則需要解析字符串,然後進行轉換。 –

+0

不起作用,它只是獲取字符串。我想出了 –

+0

謝謝你的禮貌迴應,試圖幫助你。 –

回答

0

您的代碼就相當於這一個:

private string grabString(byte[] buffer) 
{ 
    var asDecimal = string.Join(".", buffer)); 
    return (asDecimal == "0.0.0.0" ? "" : asDecimal); 
} 
相關問題