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);
Related
I need to process a numeral as a string.
My value is 0x28 and this is the ascii code for '('.
I need to assign this to a string.
The following lines do this.
char c = (char)0x28;
string s = c.ToString();
string s2 = ((char)0x28).ToString();
My usecase is a function that only accepts strings.
My call ends up looking cluttered:
someCall( ((char)0x28).ToString() );
Is there a way of simplifying this and make it more readable without writing '(' ?
The Hexnumber in the code is always paired with a Variable that contains that hex value in its name, so "translating" it would destroy that visible connection.
Edit:
A List of tuples is initialised with this where the first item has the character in its name and the second item results from a call with that character.
One of the answers below is exactly what i am looking for so i incorporated it here now.
{ existingStaticVar0x28, someCall("\u0028") }
The reader can now instinctively see the connection between item1 and item2 and is less likely to run into a trap when this gets refactored.
You can use Unicode character escape sequence in place of a hex to avoid casting:
string s2 = '\u28'.ToString();
or
someCall("\u28");
Well supposing that you have not a fixed input then you could write an extension method
namespace MyExtensions
{
public static class MyStringExtensions
{
public static string ConvertFromHex(this string hexData)
{
int c = Convert.ToInt32(hexCode, 16);
return new string(new char[] {(char)c});
}
}
}
Now you could call it in your code wjth
string hexNumber = "0x28"; // or whatever hexcode you need to convert
string result = hexNumber.ConvertFromHex();
A bit of error handling should be added to the above conversion.
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];
I have a six digit unicode character, for example U+100000 which I wish to make a comparison with a another char in my C# code.
My reading of the MSDN documentation is that this character cannot be represented by a char, and must instead be represented by a string.
a Unicode character in the range U+10000 to U+10FFFF is not permitted in a character literal and is represented using a Unicode surrogate pair in a string literal
I feel that I'm missing something obvious, but how can you get the follow comparison to work correctly:
public bool IsCharLessThan(char myChar, string upperBound)
{
return myChar < upperBound; // will not compile as a char is not comparable to a string
}
Assert.IsTrue(AnExample('\u0066', "\u100000"));
Assert.IsFalse(AnExample("\u100000", "\u100000")); // again won't compile as this is a string and not a char
edit
k, I think I need two methods, one to accept chars and another to accept 'big chars' i.e. strings. So:
public bool IsCharLessThan(char myChar, string upperBound)
{
return true; // every char is less than a BigChar
}
public bool IsCharLessThan(string myBigChar, string upperBound)
{
return string.Compare(myBigChar, upperBound) < 0;
}
Assert.IsTrue(AnExample('\u0066', "\u100000));
Assert.IsFalse(AnExample("\u100022", "\u100000"));
To construct a string with the Unicode code point U+10FFFF using a string literal, you need to work out the surrogate pair involved.
In this case, you need:
string bigCharacter = "\uDBFF\uDFFF";
Or you can use char.ConvertFromUtf32:
string bigCharacter = char.ConvertFromUtf32(0x10FFFF);
It's not clear what you want your method to achieve, but if you need it to work with characters not in the BMP, you'll need to make it accept int instead of char, or a string.
As per the documentation for string, if you want to iterate over characters in a string as full Unicode values, use TextElementEnumerator or StringInfo.
Note that you do need to do this explicitly. If you just use ordinal values, it will check UTF-16 code units, not the UTF-32 code points. For example:
string text = "\uF000";
string upperBound = "\uDBFF\uDFFF";
Console.WriteLine(string.Compare(text, upperBound, StringComparison.Ordinal));
This prints out a value greater than zero, suggesting that text is greater than upperBound here. Instead, you should use char.ConvertToUtf32:
string text = "\uF000";
string upperBound = "\uDBFF\uDFFF";
int textUtf32 = char.ConvertToUtf32(text, 0);
int upperBoundUtf32 = char.ConvertToUtf32(upperBound, 0);
Console.WriteLine(textUtf32 < upperBoundUtf32); // True
So that's probably what you need to do in your method. You might want to use StringInfo.LengthInTextElements to check that the strings really are single UTF-32 code points first.
From https://msdn.microsoft.com/library/aa664669.aspx, you have to use \U with full 8 hex digits. So for example:
string str1 = "\U0001F300";
string str2 = "\uD83C\uDF00";
bool eq = str1 == str2;
using the :cyclone: emoji.
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
suppose there is a string like this
string temp2 = "hello";
char[] m = { 'u','i','o' };
Boolean B = temp2.Compare(m);
I want to check if the string contains my array of character or not?
I am trying but it is not taking.On compiling the message
temp2.Compare(m) should be String type
is coming.
Means it follows string.compare(string);
I hope it is not the way there should be some way to do that.
edit//
I have Corrected the line String.Compare return the Boolean Value
If what you want to determine is whether the string contains any of the characters in your array, you can use the string.IndexOfAny function.
bool containsAny = temp2.IndexOfAny(m) >= 0;