C# converting string to int goes wrong - c#

I have a string that contains numbers, like so:
string keyCode = "1200009990000000000990";
Now I want to get the number on position 2 as integer, which I did like so:
int number = Convert.ToInt32(keyCode[1]);
But instead of getting 2, I get 50.
What am I doing wrong?

50 is the ascii code for char '2'. 0->48, 1->49 etc....
You can do
int number = keyCode[1]-'0';

You observed that when you do int n = Convert.ToInt32( '2' ); you get 50. That's correct.
Apparently, you did not expect to get 50, you expected to get 2. That's what's not correct to expect.
It is not correct to expect that Convert.ToInt32( '2' ) will give you 2, because then what would you expect if you did Convert.ToInt32( 'A' ) ?
A character is not a number. But of course, inside the computer, everything is represented as a number. So, there is a mapping that tells us what number to use to represent each character. Unicode is such a mapping, ASCII is another mapping that you may have heard of. These mappings stipulate that the character '2' corresponds to the number 50, just as they stipulate that the character 'A' corresponds to the number 65.
Convert.ToInt32( char c ) performs a very rudimentary conversion, it essentially reinterprets the character as a number, so it allows you to see what number the character corresponds to. But if from '2' you want to get 2, that's not the conversion you want.
Instead, you want a more complex conversion, which is the following: int n = Int32.Parse( keyCode.SubString( 1, 1 ) );

Well, You got 50 because it is the ascii code of 2.
You are getting it because you are pointing to a char and when c# converts a char to an int it gives back its ascii code. You should use instead int.Parse which takes a string.
int.Parse(keyCode[1].ToString());
or
int.Parse(keyCode.Substring(1,1));

You need
int number = (int)Char.GetNumericValue(keyCode[1]);
The cast is needed because Char.GetNumericValue returns a double.

As Ofir said, another method is int number = int.Parse(keyCode[1].ToString()).
This command can be explained like this: int is shorthand for Int32, which contains a Parse(string) method. Parse only works if the input is a string that contains only numbers, so it's not always the best to use unless TryParse (the method that checks whether you can parse a string or not) has been invoked and returns true, but in this case, since your input string is always a number, you can use Parse without using TryParse first. keyCode[1] actually implicitly converts keyCode to a char[] first so that it can retrieve a specific index, which is why you need to invoke ToString() on it before you can parse it.
This is my personal favorite way to convert a string or char to an int, since it's pretty easy to make sense of once you understand the conversions that are performed both explicitly and implicitly. If the string to convert isn't static, it may be better to use a different method, since an if statement checking whether it can be parsed or a try makes it take longer to code and execute than one of the other solutions.

Related

how to add zeros for integer variable

I'm very new to c# programming. I want to know how to add leading zeros for a integer type in c#.
ex:
int value = 23;
I want to use it like this ;
0023
Thanks in advance
You can't. There's no such contextual information in an int. An integer is just an integer.
If you're talking about formatting, you could use something like:
string formatted = value.ToString("0000");
... that will ensure there are at least 4 digits. (A format string of "D4" will have the same effect.) But you need to be very clear in your mind that this is only relevant in the string representation... it's not part of the integer value represented by value. Similarly, value has no notion of whether it's in decimal or hex - again, that's a property of how you format it.
(It's really important to understand this in reasonably simple cases like this, as it tends to make a lot more difference for things like date/time values, which again don't store any formatting information, and people often get confused.)
Note that there's one type which may surprise you: decimal. While it doesn't consider leading zeroes, it does have a notion of trailing zeroes (implicitly in the way it's stored), so 1.0m and 1.00m are distinguishable values.
Basically you want to add padding zeros.
string format specifier has a very simple method to this.
string valueAfterpadding;
int value = 23;
valueAfterpadding = value.ToString("D4");
Console.WriteLine(valueAfterpadding );
this solve your problem. just google it.
Integer wont accept leading zeros, it will only hold the real value of the integer.
The best we to have leading zeros is to convert it to string.
If you need a 4 digit value always, use the .ToString formatting to add leading 0's.
int value = 23;
var result = value.ToString("0000");
or if you want to have a leading 00 to any number, better append 00 to the string equivalent of the integer.
int value = 23;
var result = "00" + value.ToString();
This is not a programming issue. Numbers have no leading zeroes.
There are two things here that you can do:
If it is a number, then format it on the way out.
If it is something like a code (article number etc.) - those are NOT NUMBERS.
The second point is important. Things like social security numbers, part numbers etc. are strings - with only numeric characters allowed. You never add or subtract them and you must be prepared for format changes. They are not integers or any other number form to start with.

C# 7 binary literal for -1

I want to declare -1 literal using the new binary literal feature:
int x = 0b1111_1111_1111_1111_1111_1111_1111_1111;
Console.WriteLine(x);
However, this doesn't work because C# considers this as a uint literal and we get Cannot implicitly convert type 'uint' to 'int'... which is a bit strange for me since we deal with binary data.
Is there a way to declare -1 integer value using binary literal in C#?
After trying some cases, I finally found out this one
int x = -0b000_0000_0000_0000_0000_0000_0000_0001;
Console.WriteLine(x);
And as result is printed -1.
If I understand everything correct they use sing flag for -/+ so when you put 32 1 you go into uint
You can explicitly cast it, but because there's a constant term involved, I believe you have to manually specify unchecked:
int x = unchecked((int)0b1111_1111_1111_1111_1111_1111_1111_1111);
(Edited to include Jeff Mercado's suggestion.)
You can also use something like int x = -0b1 as pointed out in S.Petrosov's answer, but of course that doesn't show the actual bit representation of -1, which might defeat the purpose of declaring it using a binary literal in the first place.

C#'s Convert.ToInt32(3) converts to 51

When creating a program that takes a number (like 1253) and turns it into 125^3, I get an odd error where converting a string won't seem to work. Here is my code:
string example = "1253";
// grab all but the last character
int num = Convert.ToInt32(example.Substring(0, example.Length - 1));
Console.WriteLine(num);
// grab the last character
//int pow = Convert.ToInt32(example.Substring(example.Length - 1));
int pow = Convert.ToInt32(example[example.Length - 1]);
Console.WriteLine(pow);
// output num to the power of pow
Console.WriteLine(Math.Pow(num, pow));
Console.ReadKey();
The first initialization of the variable pow works correctly but the second one (not commented out) does not for some reason. The different ways of grabbing the last character of a string work, but for some reason with the first "3" will convert to 3, but for the latter "3" will convert to 51.
Here is the output when using the commented initialization of pow:
125
3
1953125
Here is the output when using the uncommented initialization of pow:
125
51
8.75811540203011E+106
I'm fairly new to C# so any help would be much appreciated. Thank you!
When you use an indexer on a string: example[example.Length - 1] you are returned a char of value '3' (not a string "3").
This means a different overload of Convert.ToInt32 is called with a char as the parameter. The conversion applied to a char is completely different to that which is applied to a string.
char : Converts the value of the specified Unicode character to the equivalent 32-bit signed integer.
as opposed to
string: Converts the specified string representation of a number to an equivalent 32-bit signed integer.
If you take a peek at a Unicode table, you'll see that '3' has a value of hex 33, or 51.
You might have better luck with example[example.Length - 1].ToString().
When you pass a character into Convert.ToInt32() it will convert it into its ASCII value. That's why your 3 is becoming 51.

Converting from Combobox double digit to int double digit

Min = Convert.ToInt32(cbMin.SelectedItem);
Here's my issue, using that line to convert from the combobox to the integer variable. Right now, if i select "00" or "05" from my drop down the value only comes out as "0" or "5" It only seems to happen when a number STARTS with a "0"
Am i missing something?
PS: By the way, when I setup the combobox i just used the properties section on the side and filled out the collection. Just wanted to be sure that i threw that out there.
dont convert value to integer if you want leading zero make use of string
i.ToString("00")
try this out soltuon will work for you
final code is
string s = (Convert.ToInt32(cbMin.SelectedItem)).ToString("00")
EDIT
if you alredy assinged valeu with 0 than you just need to write
string Min = cbMin.SelectedItem.ToString();
Integers don't have leading zeros. They are numeric data types. The leading zero is only possible in a string data type.
int 0 is not the same as string "0"
int 1 is not the same as string "1"
If you need to output the value with the leading 0, and never use it in mathematical claculations, you should keep it as a string. Don't convert it to an int in the first place.
If you need it as an integer to do calculations, then you need to convert it to an int, but in places where you need the leading zero, format it. Convert it back to a string and use data formatting to get the leading zero.
"1".ToString("00") will result in "01".
"15".ToString("00") will result in "15".
For more information on formatting numeric data types, see the documentation here and the Custom Numeric Format Strings (as shown in my examples above) documentation here.
There is no sense make an integer 5 as 05 in C#. But if want a string has this format, you can do:
string Min = Convert.ToInt32(cbMin.SelectedItem).ToString("00");
Or
string Min = String.Format("{0:0#}", Convert.ToInt32(cbMin.SelectedItem));

How to convert a string "001" to int 001

how do i convert a string of "001" to an int 001? using Convert.ToInt32() method or Int32.Parse() method gives the result as only 1
How could you have an int as 001? You could format it as a string with leading zeros, but the int itself is just a numeric representation. Keep in mind that the language needs a way to represent the int to you as a series of characters, and that it needs to be deterministic (because otherwise it would have no way to choose). So the standard is to not show any leading zeros.
You can't have an int with zeros in front like that - doesn't quite make sense. If the formatting is important you'll just have to leave it as a string.
1 is an integer, 001 is a string. If you are trying to display a 3-digit series as an id or similar and are incrementing you will need to convert your string "001" to an integer, increment it, then convert it back to a "0" padded string for display.
public string NextId(string currentId)
{
int i = 0;
if (int.TryParse(currentId, out i))
{
i++;
return(i.ToString().PadLeft(3,'0'));
}
throw new System.ArgumentException("Non-numeric string passed as argument");
}
There is a fundamental misunderstanding in your question. An int is a number, and in our numerical system, leading zeros on the left of the decimal point do not change the number and are therefore irrelevant. In other words, 1 is equal to 01 is equal to 001 is equal to 0001 and so forth... this may seem obvious, but it makes the point that 1 is the integer value. 001 is a string.
An integer cannot store the value 001. The result 1 is correct.
You need to elaborate on why you need the other zeros.
Whilst in byte form it will have a representation along the lines of 001 (or 0000000000000001), the runtime doesn't know which base you want to represent the number in, so the 2nd and 3rd columns (the other two zeros) are ambiguous.
an int will never be preceded with '0', only string is possible.
You can use Int32.ToString("000") to format an integer in this manner.
string one = a.ToString("000"); // 001
string two = b.ToString("000"); // 010
but you cant use like a integer 001.

Categories

Resources