Procedimiento Convertir cadenas hexadecimales en tipos numéricos (Guía de programación de C#)

En estos ejemplos se muestra cómo realizar las tareas siguientes:

  • Obtener el valor hexadecimal de cada uno de los caracteres de un elemento string.

  • Obtener el elemento char que corresponde a cada valor de una cadena hexadecimal.

  • Convertir un elemento string hexadecimal en un elemento int.

  • Convertir un elemento string hexadecimal en un elemento float.

  • Convertir una matriz de bytes en un elemento string hexadecimal.

Ejemplos

En este ejemplo se genera el valor hexadecimal de cada uno de los caracteres de string. Primero, analiza string como una matriz de caracteres. Después, llama a ToInt32(Char) en cada carácter para obtener su valor numérico. Finalmente, aplica formato al número como su representación hexadecimal en un elemento string.

string input = "Hello World!";
char[] values = input.ToCharArray();
foreach (char letter in values)
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(letter);
    // Convert the integer value to a hexadecimal value in string form.
    Console.WriteLine($"Hexadecimal value of {letter} is {value:X}");
}
/* Output:
    Hexadecimal value of H is 48
    Hexadecimal value of e is 65
    Hexadecimal value of l is 6C
    Hexadecimal value of l is 6C
    Hexadecimal value of o is 6F
    Hexadecimal value of   is 20
    Hexadecimal value of W is 57
    Hexadecimal value of o is 6F
    Hexadecimal value of r is 72
    Hexadecimal value of l is 6C
    Hexadecimal value of d is 64
    Hexadecimal value of ! is 21
 */

En este ejemplo se analiza un elemento string de valores hexadecimales y genera el carácter correspondiente a cada valor hexadecimal. Primero, llama al método Split(Char[]) para obtener cada valor hexadecimal como un elemento string individual en una matriz. Después, llama a ToInt32(String, Int32) para convertir el valor hexadecimal a un valor decimal representado como int. Muestra dos maneras distintas de obtener el carácter correspondiente a ese código de carácter. En la primera técnica se usa ConvertFromUtf32(Int32), que devuelve el carácter correspondiente al argumento de tipo entero como string. En la segunda técnica, int se convierte de manera explícita en un elemento char.

string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (string hex in hexValuesSplit)
{
    // Convert the number expressed in base-16 to an integer.
    int value = Convert.ToInt32(hex, 16);
    // Get the character corresponding to the integral value.
    string stringValue = Char.ConvertFromUtf32(value);
    char charValue = (char)value;
    Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
                        hex, value, stringValue, charValue);
}
/* Output:
    hexadecimal value = 48, int value = 72, char value = H or H
    hexadecimal value = 65, int value = 101, char value = e or e
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 6F, int value = 111, char value = o or o
    hexadecimal value = 20, int value = 32, char value =   or
    hexadecimal value = 57, int value = 87, char value = W or W
    hexadecimal value = 6F, int value = 111, char value = o or o
    hexadecimal value = 72, int value = 114, char value = r or r
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 64, int value = 100, char value = d or d
    hexadecimal value = 21, int value = 33, char value = ! or !
*/

En este ejemplo se muestra otra manera de convertir un string hexadecimal en un entero mediante la llamada al método Parse(String, NumberStyles).

string hexString = "8E2";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(num);
//Output: 2274

En el siguiente ejemplo se muestra cómo convertir un string hexadecimal en un elemento float con la clase System.BitConverter y el método UInt32.Parse.


string hexString = "43480170";
uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);

byte[] floatVals = BitConverter.GetBytes(num);
float f = BitConverter.ToSingle(floatVals, 0);
Console.WriteLine("float convert = {0}", f);

// Output: 200.0056

En el ejemplo siguiente se muestra cómo convertir una matriz byte en una cadena hexadecimal mediante la clase System.BitConverter.

byte[] vals = [0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD];

string str = BitConverter.ToString(vals);
Console.WriteLine(str);

str = BitConverter.ToString(vals).Replace("-", "");
Console.WriteLine(str);

/*Output:
  01-AA-B1-DC-10-DD
  01AAB1DC10DD
 */

En el ejemplo siguiente se muestra cómo convertir una matriz byte en una cadena hexadecimal mediante una llamada al método Convert.ToHexString introducido en .NET 5.0.

byte[] array = [0x64, 0x6f, 0x74, 0x63, 0x65, 0x74];

string hexValue = Convert.ToHexString(array);
Console.WriteLine(hexValue);

/*Output:
  646F74636574
 */

Vea también