2014-02-16 52 views
2

你如何轉換爲字符串整數轉換的Int64爲String?它可以反過來工作,但不是這樣。C#使用強制

string message 
Int64 message2; 
message2 = (Int64)message[0]; 

如果消息是「hello」,則輸出爲104作爲數字;

如果我做

string message3 = (string)message2; 

我得到一個錯誤,說你不能長轉換爲字符串。爲什麼是這樣。方法.ToString()不起作用,因爲它只將數字轉換爲字符串,所以它仍然會顯示爲「104」。與Convert.ToString()一樣。我如何使它從104再次說出「你好」?在C++中,它可以讓你施展這種方法而不是在C#

回答

3

message[0]給出了從字符串的第一個字母爲char,所以你鑄造charlong,不stringlong

嘗試再次鑄造回char然後串連所有字符得到整個字符串。

2

ToString()一樣工作正常。您的錯誤是在轉換爲整數。

正是你怎麼能指望存儲在一個長期的非數字的數字組成的字符串?如果您想將數字視爲字節數組,您可能對BitConverter感興趣。

如果你想一個數字ASCII代碼轉換爲字符串,嘗試

((char)value).ToString() 
1

試試這個方法:

string message3 = char.ConvertFromUtf32(message2); 
  • 104是 「H」,而不是價值的「hello 」。
1

沒有字符串的整數表示形式,只有字符。因此,如由其他人指出,104是不是「你好」(字符串),但的「H」(一個char)的值(見ASCII chart here)。

我不能完全明白你爲什麼會想一個字符串轉換成int數組,然後回一個字符串,但這樣做的方式,它是通過串運行,並獲得內部 - 每個字符的值,然後將這些int值重新轉換爲char值並將它們連接起來。因此,像

string str = "hello" 
List<int> N = new List<int>(); 
//this creates the list of int-values 
for(int i=0;i<str.Count;i++) 
    N.Add((int)str[i]); 
//and this joins it all back into a string 
string newString = ""; 
for(int i=0;i<str.Count;i++) 
    newString += (char)N[i]; 
2

另一種替代的方法是使用ASCII.GetBytes方法如下

string msg1 ="hello"; 
byte[] ba = System.Text.Encoding.ASCII.GetBytes(msg1); 
//ba[0] = 104 
//ba[1] = 101 
//ba[2] = 108 
//ba[3] = 108 
//ba[4] = 111 

string msg2 =System.Text.Encoding.ASCII.GetString(ba); 
//msg2 = "hello"