Reputation: 15345
I am coding a converter in C# to convert from integer, binary and hexadecimal into same formats. Of course the input format and the output format is given.
Another interesting point is that my input is a string
and my output is also a string
.
So, now I wonder if there is a way to do all those conversions using the same function because in all questions I explored some solutions are given for only one of my 6 cases and I don't find it really elegant.
To summarize:
Input String | Output String -------------|-------------- int32 | hexa int32 | binary binary | int32 binary | hexa hexa | int32 hexa | binary
EDIT: All exceptions will be handled with try-catch if necessary.
Upvotes: 0
Views: 485
Reputation: 60276
Make it a two-step process: parsing a string from one of the three formats, and then convert to one of the three formats.
To parse, you can use the respective Parse
(or TryParse
if you want to avoid exceptions) methods which exist for the different numeric types. On integer types, you can use the NumberStyles.HexNumber
to parse from a hex number.
To convert to a string, use the overloaded ToString
with the appropriate culture and format.
Note that you can do type conversions through the IConvertible
interface, which is supported by all native number types.
Here's some pseudocode (will not compile but should illustrate the points made):
enum NumberKind {
Int32,
Decimal,
Hexa
}
string ConvertNumber(NumberKind inputKind, string inputValue, NumberKind outputKind) {
IConvertible intermediate;
switch (inputKind) {
case NumberKind.Int32:
intermediate = Int32.Parse(inputValue, NumberStyles.Integer, CultureInfo.InvariantCulture);
break;
case NumberKind.Decimal:
intermediate = Decimal.Parse(inputValue, NumberStyles.Number, CultureInfo.InvariantCulture);
break;
case NumberKind.Hexa:
intermediate = Int32.Parse(inputValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
break;
}
switch (outputKind) {
case NumberKind.Int32:
return intermediate.ToInt32().ToString("D", CultureInfo.InvariantCulture);
case NumberKind.Decimal:
return intermediate.ToDecimal().ToString("G", CultureInfo.InvariantCulture);
case NumberKind.Hexa:
return intermediate.ToInt32().ToString("X", CultureInfo.InvariantCulture);
}
}
Upvotes: 1