nurtul
nurtul

Reputation: 408

C# Convert Int64 to String using a cast

How do you convert an integer to a string? It works the other way around but not this way.

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

If the message is "hello", the output is 104 as a number;

If I do

string message3 = (string)message2;

I get an error saying that you cant convert a long to a string. Why is this. The method .ToString() does not work because it converts just the number to a string so it will still show as "104". Same with Convert.ToString(). How do I make it say "hello" again from 104? In C++ it allows you to cast such methods but not in C#

Upvotes: 2

Views: 5628

Answers (5)

Damith
Damith

Reputation: 63065

Another alternative approach is using ASCII.GetBytes method as below

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"

Upvotes: 2

Wasabi
Wasabi

Reputation: 3061

There is no integer representation of a string, only of a char. Therefore, as stated by others, 104 is not the value of "hello" (a string) but of 'h' (a char) (see the ASCII chart here).

I can't entirely think of why you'd want to convert a string to an int-array and then back into a string, but the way to do it would be to run through the string and get the int-value of each character and then reconvert the int-values into char-values and concatenate each of them. So something like

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];

Upvotes: 1

Bappi Datta
Bappi Datta

Reputation: 1380

Try this method:

string message3 = char.ConvertFromUtf32(message2);
  • 104 is the value of "h" not "hello".

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

message[0] gives first letter from string as char, so you're casting char to long, not string to long.

Try casting it back to char again and then concatenate all chars to get entire string.

Upvotes: 3

Ben Voigt
Ben Voigt

Reputation: 283614

ToString() is working exactly correctly. Your error is in the conversion to integer.

How exactly do you expect to store a string composed of non-numeric digits in a long? You might be interested in BitConverter, if you want to treat numbers as byte arrays.

If you want to convert a numeric ASCII code to a string, try

((char)value).ToString()

Upvotes: 2

Related Questions