If I have a string (010) and i want to add 1 to it (011) what value type should i use to convert this string into a number for adding and at the same time preserve the whole number and not 10 + 1 = 11.
-
Are these strings binary representations?Greg Dean– Greg Dean2008-10-16 16:55:34 +00:00Commented Oct 16, 2008 at 16:55
-
gdean2323 question is appropriate. What is the expected result of this sum: 011 + 1 ? Would you expect 012 or 100 ?FOR– FOR2008-10-16 16:59:49 +00:00Commented Oct 16, 2008 at 16:59
10 Answers
You could use something like this:
string initialValue = "010";
int tempValue = Int.Parse(initialValue) + 1;
string newValue = tempValue.ToString("000");
You do your math as normal and then just return your string to its previous format using the number formatting feature of the .ToString()
Comments
if (int.TryParse(str, out i))
str = (i + 1).ToString("000");
HTH.
(edit: fixed the problems pointed out by BoltBait and steffenj)
It looks like you're trying to work with binary numbers encoded as strings (hmmm. maybe there's a place for clippy in visual studio). You can use Convert() methods to do this for you. The 2 is used to indicate base-2 formatting. If you need the string to be a certain size, you may have to add zero padding.
string s = "010";
s = Convert.ToString(Convert.ToInt32("010", 2) + 1, 2);
Comments
int value = 10;// or, int value = Convert.ToInt32("010");
value += 1;
string text = value.ToString("000");
The "000" in the ToString call is called a format string. It tells .net how to print out the number. In this case, the character '0' indicates that for the number at this position, it should display a zero if the number would not otherwise be displayed.
Comments
Here's how I'd do it:
public string AddOne (string text)
{
int parsed = int.Parse(text);
string formatString = "{0:D" + text.Length + "}";
return string.Format(formatString, parsed + 1);
}
By putting the length of the input text into the format string, you can ensure that your resulting string is the same length as your input.
Depending on your needs, you may need exception handling around the int.Parse. I thought I'd let the exception bubble up as the exceptions thrown (ArgumentException or ArgumentNullException) by int.Parse would be the same exceptions that I would throw in my method anyway.
Comments
Well, you could always create your own struct which contained the int and required output length (based on the input length). Or just remember it very temporarily, as shown below... it depends on how often you need this.
string ParseAndAdd(string text, int add)
{
int parsed = int.Parse(text);
return (parsed + add).ToString().PadLeft(text.Length, '0');
}