Convert String Value to Hexadecimal without changing format

4

I'm 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 Endereco variable of a String , which will be obtained by reading a web form. How could I get 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.

    
asked by anonymous 31.01.2017 / 12:25

2 answers

5

You can do 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}");
    }
}

See running on .NET Fiddle . And at Coding Ground . Also I put it in GitHub for future reference .

If you are not sure that string has a convertible number correctly then it is best to use TryParse() .

Obviously after converting the string to a number, it is just this, a number, has no formatting, it is not decimal or hexadecimal, it's just a number. If you want to see it as hex you need to have it printed like this and that's what I did in WriteLine() . I used interpolation with formatting (the :X ) . This prints a hexadecimal representation of the number. If you do not use this way the default is to print the value in decimal representation.

If you do not want to print, just to convert is this:

int.Parse("1A3B", NumberStyles.HexNumber)
    
31.01.2017 / 12:38
0

If you receive a string representing the address in hexadecimal. The most suitable way would be to first convert this string to an integer value, which may not be trivial. With the number converted to integer, the hexadecimal is only the representation of the value: String 1A3B = 6715, logo 6715 == 0x1A3B.

    
31.01.2017 / 12:38