2014-03-26 63 views
2

我試圖通過8位(每個8位= 1個ASCII字符)將位串轉換爲ASCII字符。將位串轉換爲字符

 public string BitsToChar(string InpS) 
     { 
      string RetS = ""; 
      for (int iCounter = 0; iCounter < InpS.Length/8; iCounter++) 
       RetS = System.String.Concat(RetS, (char)Convert.ToByte(InpS.Substring(iCounter * 8, 8)), 2);     
      return RetS; 
     } 

它引發System.OverflowException:值對於無符號字節來說太大或太小。

對於我來說不清楚8位二進制字符串的8位部分對於8位字節類型來說可能太小或太大。

任何想法?謝謝。

+0

Convert.ToByte()使用'decimal'表示,而不是'binary';所以例如「01000000」被視爲「一百萬」,並導致整數溢出 –

+0

我認爲Convert.ToByte(str,2),我使用,與二進制。 – user3462831

+0

這最初是一個字節數組?這很容易理解爲ASCII並從中得到一個字符串。 – BradleyDotNET

回答

1

嘗試類似的東西:

private static Char ConvertToChar(String value) { 
     int result = 0; 

     foreach (Char ch in value) 
     result = result * 2 + ch - '0'; 

     return (Char) result; 
    } 

    public string BitsToChar(string value) { 
     if (String.IsNullOrEmpty(value)) 
     return value; 

     StringBuilder Sb = new StringBuilder(); 

     for (int i = 0; i < value.Length/8; ++i) 
     Sb.Append(ConvertToChar(value.Substring(8 * i, 8))); 

     return Sb.ToString(); 
    } 

...

String result = BitsToChar("010000010010000001100010"); // <- "A b" 
0

做這樣的事情

public string BitsToChar(string InpS) 
{ 
    string RetS = ""; 
    foreach (char c in InpS) 
    { 
    RetS = RetS + System.Convert.ToInt32(c); 
    } 

    return RetS; 
} 
0

嘗試類似的東西:

public static string BitsToChar(string bitString) 
    { 
     var retString = new StringBuilder(); 

     foreach (Match match in Regex.Matches(bitString, "[01]{8}")) // 8 is size of bits 
     { 
      retString.Append((Char)Convert.ToByte(match.Value, 2)); 
     } 

     return retString.ToString(); 
    }