Convert alphabetic string into Integer in C# - c#

Is it possible to convert alphabetical string into int in C#? For example
string str = "xyz";
int i = Convert.ToInt32(str);
I know it throws an error on the second line, but this is what I want to do.
So how can I convert an alphabetical string to integer?
Thanks in advance

System.Text.Encoding ascii = System.Text.Encoding.ASCII;
string str = "xyz";
Byte[] encodedBytes = ascii.GetBytes(str);
foreach (Byte b in encodedBytes)
{
return b;
}
this will return each characters ascii value... its up to you what you want to do with them

To answer the literal questions that you have asked
Is it possible to convert alphabetical string into int in C#?
Simply put... no
So how can I convert an alphabetical string to integer?
You cannot. You can simply TryParse to see if it will parse, but unless you calculate as ASCII value from the characters, there is no built in method in c# (or .NET for that matter) that will do this.

You can check whether a string contains a valid number using Int32.TryParse (if your questions is about avoiding an exception to be thrown):
int parsed;
if (!Int32.TryParse(str, out parsed))
//Do Something

Related

How to convert unicode set from db to characters?

I need to convert unicode characters that I take from the database field to a string value. In the database field unicode characters are in format U+0024 and next I get \u0024 format but I cannot convert it.
string a = "U+0024";
string b = a.Remove(0, 2);
string c = #"\u" + b;
string d = System.Uri.UnescapeDataString(c);
Console.WriteLine(d);
// There is \u0024 in output
string e =System.Uri.UnescapeDataString(\u0024);
Console.WriteLine(e);
//There is $ in output that I would like to
The strings you got from your DB seems to be Unicode codepoints, as they are in the format U+XXXX.
There is a very useful method called char.ConvertFromUtf32 that converts a Unicode code point to a string containing a single char, or a surrogate pair of chars.
This method accepts an int as parameter, so you would need to convert your b string (which is in hexadecimal) into an int.
int codepoint = Convert.ToInt32(b, 16);
Then, pass it to ConvertFromUtf32:
string result = char.ConvertFromUtf32(codepoint);

String with index conversion or array of numbers

Why i can't convert this string to a number? Or how to make a array of numbers from this string.
string str = "110101010";
int c = Int32.Parse(str[0]);
str is a string so str[0] returns a char and the Parse method doesnt take a char as input but rather a string.
if you want to convert the string into an int then you would need to do:
int c = Int32.Parse(str); // or Int32.Parse(str[0].ToString()); for a single digit
or you're probably looking for a way to convert all the individual numbers into an array which can be done as:
var result = str.Select(x => int.Parse(x.ToString()))
.ToArray();
I assume you are trying to convert a binary string into its decimal representation.
For this you could make use of System.Convert:
int c = Convert.ToInt32(str, 2);
For the case that you want to sum up all the 1s and 0s from the string you could make use of System.Linq's Select() and Sum():
int c = str.Select(i => int.Parse(i.ToString())).Sum();
Alternatively if you just want to have an array of 1s and 0s from the string you could omit the Sum() and instead enumerate to an array using ToArray():
int[] c = str.Select(i => int.Parse(i.ToString())).ToArray();
Disclaimer: The two snippets above using int.Parse()would throw an exception if str were to contain a non-numeric character.
Int32.Parse accepts string argument, not char which str[0] returs.
To get the first number, try:
string str = "110101010";
int c = Int32.Parse(str.Substring(0, 1));

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#
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.
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()
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"
Try this method:
string message3 = char.ConvertFromUtf32(message2);
104 is the value of "h" not "hello".
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];

the equivalent of sscanf_s in C#?

UnlockOffset is DWORD. thisKey is a char[5]
if(EOF == sscanf_s(thisKey, "%d", &UnlockOffset))
How would the above code be done in c# ?
DWORD was converted to UInt32 and thiskey remained char array but I still dont understand the sscanf_s.
PS: I did check MSDN but was not able to understand it very well which was why I posted it here.
sscanf_s basically reads a string and extracts stuff that matches the format string. It'll return EOF if it couldn't extract stuff to match all the format thingies.
You could do something like
string str = new string(thisKey);
if (!UInt32.TryParse(str, out UnlockOffset))
which would accomplish something similar, but it might be more or less strict. UInt32.TryParse returns true if it could convert the string and false if it couldn't, so checking for EOF would be equivalent to seeing whether TryParse is false.
Typically, you would use UInt32.Parse (or TryParse) to pull the information out of a string. It is rare that char[] is used to store string values in C#, as string is more appropriate.
Since everyone has already mentioned uint.Parse (and uint.TryParse), you can convert your char array to an integer like this:
uint UnlockOffset = 0;
foreach (char digit in thisKey)
{
UnlockOffset *= 10;
UnlockOffset += (uint)(digit - '0');
}
If thisKey is "123 456 739" then sscanf_s(thisKey, "%d", &UnlockOffset)) would get 123 into UnlockOffset
Here's an approximate equivalent
string str = new string(thisKey);
string[] strAr = str.Split(' ');
UnlockOffset = Convert.ToUInt32(strAr!=null ? strAr[0] : str);

int to hex string

I need to convert an int to hex string.
When converting 1400 => 578 using ToString("X") or ToString("X2") but I need it like 0578.
Can anyone provide me the IFormatter to ensure that the string is 4 chars long?
Use ToString("X4").
The 4 means that the string will be 4 digits long.
Reference: The Hexadecimal ("X") Format Specifier on MSDN.
Try the following:
ToString("X4")
See The X format specifier on MSDN.
Try C# string interpolation introduced in C# 6:
var id = 100;
var hexid = $"0x{id:X}";
hexid value:
"0x64"
Previous answer is not good for negative numbers. Use a short type instead of int
short iValue = -1400;
string sResult = iValue.ToString("X2");
Console.WriteLine("Value={0} Result={1}", iValue, sResult);
Now result is FA88
Convert int to hex string
int num = 1366;
string hexNum = num.ToString("X");

Categories

Resources