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.
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(orTryParseif you want to avoid exceptions) methods which exist for the different numeric types. On integer types, you can use theNumberStyles.HexNumberto parse from a hex number.To convert to a string, use the overloaded
ToStringwith the appropriate culture and format.Note that you can do type conversions through the
IConvertibleinterface, which is supported by all native number types.Here’s some pseudocode (will not compile but should illustrate the points made):