Convert string value to hexadecimal without changing format

Asked

Viewed 396 times

4

I am using the following code in a Class.

  public Int16 Endereco = 0x7302;
  byte[] Data = BitConverter.GetBytes(Endereco);
  Array.Reverse(Data);
  [...]

I would like to receive the value for the variable Endereco of a String, which will be obtained by reading a web form. How could I receive the string and convert the same number to hexadecimal, for example:

  String entrada = "7302"; 

Convert to Address as 0x7302, or

 String entrada = "1A3B"

Convert to address as 0x1A3B.

2 answers

6


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.

0

If you receive a string representing the address in hexadecimal. The most indicated path would be to first convert this string to an integer value, something that may not be trivial. With the number converted to integer, the hexadecimal will be only the value representation: String 1A3B = 6715, so 6715 == 0x1A3B.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.