2014-01-22 148 views
0

下面是代碼(十六進制轉換爲十進制)我正在努力解決.. 我發現了錯誤,我在代碼中已經註釋了位置..C#編碼:十六進制到十進制&字符編碼

請提供一個解決方案,以糾正..

static void Main(string[] args) 
    { 

     byte[] byteData; 
     int n; 
     byteData = GetBytesFromHexString("001C0014500C0A5B06A4FFFFFFFFFFFFFFFFFFFFFFFFFFFF"); 
     n = byteData.Length; 
     Console.WriteLine(n); 
     string s = System.Text.Encoding.UTF8.GetString(byteData, 0, n); //error 
     Console.WriteLine(s); 
     Console.ReadLine(); 
    } 

    public static byte[] GetBytesFromHexString(string hexString) 
    { 
     //MessageBox.Show("getbytes "); 
     if (hexString == null) 
      return null; 

     if (hexString.Length % 2 == 1) 
      hexString = '0' + hexString; // Up to you whether to pad the first or last byte 

     byte[] data = new byte[hexString.Length/2]; 

     for (int i = 0; i < data.Length; i++) 
     { 
      data[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); 
      Console.WriteLine(data[i]); 
     } 

什麼我得到的輸出是: 「\ 0 \ 0 P \˚F\ n [ 「 轉換後的十進制值未被編碼。

UPDATE: 預期輸出爲 「0 28 0 20 80 12 10 91 6 164 255 255 255 255 255 255 255 255 255 255 255 255 255 255」

+2

你從'Console.WriteLine(S)有什麼期望輸出;'? –

+0

檢查此鏈接 http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hexadecimal-and-decimal-in-c –

+0

我得到System.Byte []這是沒有得到編碼.. – user3222857

回答

1

而不是

string s = System.Text.Encoding.UTF8.GetString(byteData, 0, n); 

string s = String.Join(" ", byteData); 
+0

我正在獲取輸出作爲System.Byte [] ..在方法數據已經返回System.Byte [] ..我還沒有得到輸出.. – user3222857

+0

@ user3222857你接受答案,但評論說你沒有得到輸出。澄清你目前的狀態,如果你仍然需要幫助。 –

+0

謝謝我得到了輸出..我有一個疑問,字符串s = System.Text.Encoding.UTF8.GetString(byteData,0,n); 爲什麼這段代碼不起作用? – user3222857

0

可以使用此並嘗試播放與基數(在這種情況下是2)。我曾經寫過的這段代碼一直在幫助我。

private void ConvHexStringToBitString(ref string strErrorBitMask) 
    { 
     try 
     { 
      string strTempStr = strErrorBitMask; 
      if (strTempStr != string.Empty) 
      { 
       strTempStr = Convert.ToString(Convert.ToInt32(strTempStr.Replace(" ", "0"), 16), 2); 
      } 
      strErrorBitMask = strTempStr.PadLeft(32, '0'); 

     } 
     catch (Exception ex) 
     { 
      LogWithMsg(ex); 
     } 
    } 
相關問題