Is there a "Number" struct/class in .NET?
I am attempting to store a variable length number that can have leading zeros as a part of that number.
Is there a class in the .NET framework capable of storing values like this without losing information about leading zeros, and could surpass the upper limit of a long?
I am currently storing them in a class like this, is there any way I could write this class better in the event there isn't some struct or class available in the BCL:
[Serializable]
public class Number
{
public int[] Array { g开发者_StackOverflow社区et; set; }
public int Length { get { return Array.Length; } }
public Number(string number)
{
Array = new int[number.Length];
for (int i = 0; i < number.Length; i++)
{
Array[i] = Convert.ToInt32(number[i].ToString());
}
}
public Number(int[] array)
{
Array = array;
}
public int ToInt()
{
return Convert.ToInt32(ToString());
}
public override string ToString()
{
StringBuilder sb = new StringBuilder(Array.Length);
foreach (int i in Array)
sb.Append(i);
return sb.ToString();
}
}
The ability to use this as a struct would be very useful, as would the ability to check equality easily.
Items in bold/italic are the requirements of such a class.
I'd suggest taking a look at this question about big integers in C#. You could expand them for the leading zeros issue.
I see a number of problems with your class that should be addressed with the redesign.
- Your class represents a value and is mutable.
- The constructor taking an int array parameter only copies the reference.
- The value can be larger than long but is returned as an int from the ToInt() method.
The first thing I would do to shrink the size of this class is use the array of integers as a constant stream of bits which make up a binary representation of your number. This would take a lot more care in order to ensure correctness of any desired operations, but would save you a significant amount of space. If you do that, I would also store a variable to keep track of leading 0's, or perhaps a variable "total digits" semantics.
Sorry this isn't an answer to your question, but hopefully it will help you in redesigning this your class.
The BigInteger in .Net 4.0 addresses your upper limit requirement.
I think you'd still need a class like this to handle your leading zeros requirement.
Until BigInteger is openly available, I would create your own class/struct with one public string property to get/set the initial number (this will maintain your leading zeros). Then have a ReadOnly property that parses the string and returns an IntX instance.
精彩评论