2013-08-27 188 views
1

這裏是我的問題: 我有,我認爲它是二進制字符串:字符串類型轉換C#

zv�Q6��.�����E3r 

我想這個字符串轉換的東西可以閱讀。我怎樣才能在C#中做到這一點?

+3

您需要知道使用哪種編碼。 –

+0

我記得我在這個例子中使用了PHP的bin2hex函數,並得到了適當的轉換。這是否意味着我應該在C#中將此字符串轉換爲十六進制? – A23149577

回答

1

您可以嘗試枚舉(測試)所有可用的編碼,並找出編碼合理文本的 。不幸的是,當它不是一個絕對的解決方案: 它可能是一個錯誤轉換的信息損失。

public static String GetAllEncodings(String value) { 
     List<Encoding> encodings = new List<Encoding>(); 

     // Ordinary code pages 
     foreach (EncodingInfo info in Encoding.GetEncodings()) 
     encodings.Add(Encoding.GetEncoding(info.CodePage)); 

     // Special encodings, that could have no code page 
     foreach (PropertyInfo pi in typeof(Encoding).GetProperties(BindingFlags.Static | BindingFlags.Public)) 
     if (pi.CanRead && pi.PropertyType == typeof(Encoding)) 
      encodings.Add(pi.GetValue(null) as Encoding); 

     foreach (Encoding encoding in encodings) { 
     Byte[] data = Encoding.UTF8.GetBytes(value); 
     String test = encoding.GetString(data).Replace('\0', '?'); 

     if (Sb.Length > 0) 
      Sb.AppendLine();  

     Sb.Append(encoding.WebName); 
     Sb.Append(" (code page = "); 
     Sb.Append(encoding.CodePage); 
     Sb.Append(")"); 

     Sb.Append(" -> "); 
     Sb.Append(test); 
     } 

     return Sb.ToString(); 
    } 

    ... 


// Test/usage 

    String St = "Некий русский текст";  // <- Some Russian Text 
    Byte[] d = Encoding.UTF32.GetBytes(St); // <- Was encoded as UTF 32 
    St = Encoding.UTF8.GetString(d);  // <- And erroneously read as UTF 8 

    // Let's see all the encodings: 
    myTextBox.Text = GetAllEncodings(St); 

    // In the myTextBox.Text you can find the solution: 
    // .... 
    // utf-32 (code page = 12000) -> Некий русский текст 
    // .... 
1
byte[] hexbytes = System.Text.Encoding.Unicode.GetBytes(); 

這給你的字符串的十六進制字節,但你必須知道你的字符串的編碼,並用'Unicode'代替。