Convert a hexadecimal string to a byte and vice versa

-1

Hi, I want to know how to go from a hexadecimal that is a string to a byte. For example "0x0A" I want to get a 10. How do I do it?

I've been trying for a while with the Convert method, implicit conversions, etc. But the user enters 0x0A and not only 0A and I do not know how to do it without doing a foreach running the entire string.

The error I get is that the string does not have the correct format. It says it's a Date Time .

This is the code

ConfData.MyAdd.NodeA_Add = Byte.Parse(textBox_NodoA.Text, System.Globalization.NumberStyles.HexNumber);
    
asked by Xim123 14.02.2018 в 11:41
source

3 answers

2

These two methods can help you (take a look and modify them to help you)

Example for converting from String to Hex

 private static string StringToHexConvertidor(string cadenaAConvertir)
    {
        char[] valores = cadenaAConvertir.ToCharArray();
        var resultado = new StringBuilder();
        foreach (char caracter in valores)
        {
            int valorInt32 = Convert.ToInt32(caracter);
            string valorHex = String.Format("{0:X}", valorInt32);
            resultado.Append(valorHex);
            resultado.Append(" ");
        }
        return resultado.ToString();
    }

Example for converting from Hex to String

 private static string HexToStringConvertidor(string cadenaHex)
    {
        string[] valores = cadenaHex.Split(" ");
        var resultado = new StringBuilder();
        foreach (String hex in valores)
        {
            if (!string.IsNullOrEmpty(hex))
            {
                int valorInt16 = Convert.ToInt32(hex, 16);
                string cadenaValor = Char.ConvertFromUtf32(valorInt16);
                resultado.Append(cadenaValor);
            }
        }
        return resultado.ToString();
    }

I leave the complete example in C # with a console app here

  • HexToStringConverter.cs link

This doc can help you

I hope it will help or guide you.

    
answered by 14.02.2018 в 12:10
1

You can convert a hexadecimal string to a byte using the Parse method of the class% Byte :

Byte.Parse("0A", System.Globalization.NumberStyles.HexNumber)

Yes, without the prefix "0x".

To do the inverse conversion you only have to use the ToString method with the "X2" format:

((Byte)10).ToString("X2")
    
answered by 14.02.2018 в 12:10
1

The problem is that the method Parse of Byte expects a string that does not start with 0x , and therefore gives a syntax exception.

The simplest solution is to use the method Replace of string , which substitutes the string you indicate for another, and if the string to search does not appear, it simply returns the original. In this case, we look for 0x and replace it with an empty string:

ConfData.MyAdd.NodeA_Add = Byte.Parse(textBox_NodoA.Text.Replace("0x",""), System.Globalization.NumberStyles.HexNumber);
    
answered by 15.02.2018 в 09:02