Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#

like image 588
nurtul Avatar asked Feb 05 '26 23:02

nurtul


2 Answers

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.

like image 114
MarcinJuraszek Avatar answered Feb 07 '26 11:02

MarcinJuraszek


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()
like image 42
Ben Voigt Avatar answered Feb 07 '26 13:02

Ben Voigt