You can do it like this:
using static System.Console;
using System.Globalization;
public class Program {
public static void Main() {
WriteLine($"{int.Parse("7302", NumberStyles.HexNumber):X}");
WriteLine($"{int.Parse("1A3B", NumberStyles.HexNumber):X}");
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
If you’re not sure string has a convertible number correctly so it is better to use TryParse()
.
Obviously after converting the string for a number, it is just this, a number, has no formatting, it is not decimal or hexadecimal, it is only a number. If you want to see it as hexadecimal you need to have it printed like this and that’s what I did on WriteLine()
. I used interpolation with formatting (the :X
). Thus prints a hexadecimal representation of the number. If not to use this way the default is to print the value in decimal representation.
If you don’t want to print, just to convert:
int.Parse("1A3B", NumberStyles.HexNumber)
Thank you very much, it worked for what I needed.
– Elliot Alderson