2016-04-09 66 views
0

我試圖將字符串轉換成ASCII和我加轉換的一個按鈕,ASCII和兩個文本框爲ASCII:什麼我應該需要得到如何轉換字符串在.NET

例如: for input [email protected]我需要得到:116 101 120 116 064 103 103 046 099 111 109 由於某種原因我總是得到78-74-40-67-67-2E-63-6F-6D

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace ascii 
{ 
    public partial class WebForm1 : System.Web.UI.Page 
    { 

    protected void Page_Load(object sender, EventArgs e) 
    { 
    } 

    protected void TextBox1_TextChanged(object sender, EventArgs e) 
    { 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     foreach (char c in TextBox1.Text) 
     { 
      TextBox3.Text = Encoding.ASCII.GetString(new byte[] { }); 
     } 
    } 

    protected void TextBox3_TextChanged(object sender, EventArgs e) 
    { 
    } 

    } 
} 

非常感謝您的幫助!

+5

字符串已經用Unicode代表,它是ASCII的超集。你究竟想達到什麼目的?您是否想將您的字符顯示爲一系列ASCII碼? – Douglas

+1

除非TextBox3.Text包含有效數字,否則int.Parse將會失敗。您需要進一步解釋您究竟想要做什麼 –

+0

您只能將字符串的字符轉換爲ascii int。你的意思是:'int.Parse(c)'? – sthomps

回答

0

假設你想要的字符轉換爲ASCII碼和小數施展代碼:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    TextBox3.Text = String.Join(" ", Encoding.ASCII.GetBytes(TextBox1.Text)); 
} 

請注意,該代碼首先將文本轉換爲ASCII,它僅覆蓋範圍從0至127個字符,所以這取決於你的意思是「ASCII」。如果你只想要代碼點的Unicode編號表示,請使用Douglas的答案。

+0

謝謝,它帶給我信息錯誤BitConverter.ToString(Encoding.ASCII.GetString(TextBox1.Text)); 「不能從字符串轉換爲字節[]」 – user3385217

+0

@ user3385217對不起,編輯。 – IllidanS4

+0

'BitConverter'的輸出是十六進制。 –

2

假設你的字符串只包含ASCII字符,你可以使用:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    TextBox3.Text = string.Join(" ", TextBox1.Text.Select(c => (int)c)); 
} 

如果你的字符串包含非ASCII字符,那麼他們的UTF-16編碼單元將被退回。如果這不是你想要的,你應該包括一個支票:

if (TextBox1.Text.Any(c => c > 127)) 
     TextBox3.Text = "Invalid string"; 
相關問題