Compartilhar via


Como: Converter entre cadeias de caracteres hexadecimal e tipos numéricos (guia de programação translation from VPE for Csharp)

Esses exemplos mostram como executar as seguintes tarefas:

  • Obter o valor hexadecimal de cada caractere em um seqüência de caracteres.

  • Obter o char que corresponde a cada valor em uma string hexadecimal.

  • Converter um hexadecimal string para um int.

  • Converter um hexadecimal string para um float.

  • Converter um byte array um hexadecimal string.

Exemplo

Este exemplo produz o valor hexadecimal de cada caractere em um string. Primeiro, ele analisa o string para uma matriz de caracteres. Em seguida, ele chama ToInt32(Char) em cada caractere para obter o valor numérico. Por fim, ele formata o número sistema autônomo sua representação hexadecimal em um 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 decimal value to a hexadecimal value in string form.
    string hexOutput = String.Format("{0:X}", value);
    Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
}
/* 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
 */

Este exemplo analisa um string de valores de hexadecimal e gera o caractere correspondente a cada valor hexadecimal. Primeiro, ele chama o Split(array<Char[]) método obter cada valor hexadecimal sistema autônomo um indivíduo string em uma matriz. Em seguida, ele chama ToInt32(String, Int32) Para converter o valor hexadecimal em um valor decimal representado sistema autônomo um int.Ele mostra duas maneiras diferentes para obter o caractere correspondente a esse código de caractere.A primeira técnica usa ConvertFromUtf32(Int32), que retorna o caractere correspondente ao argumento de inteiro sistema autônomo um string. A segunda técnica explicitamente projeta o int para um 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 !
*/

Este exemplo mostra uma outra maneira de converter um hexadecimal string como um inteiro, chamando o Parse(String, NumberStyles) método.

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

O exemplo a seguir mostra como converter um hexadecimal string para um float usando o System.BitConverter classe e o Int32.Parse método.

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            

O exemplo a seguir mostra como converter um byte uma seqüência hexadecimal, usando o arraySystem.BitConverter classe.

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
 */

Consulte também

Tarefas

Como: Determinar se uma string representa um valor numérico (guia de programação translation from VPE for Csharp)

Conceitos

Seqüências de Caracteres de Formato Numérico Padrão

Referência

Tipos (guia de programação translation from VPE for Csharp)

Date

History

Motivo

Julho de 2008

Adicionados dois últimos exemplos de código.

Correção de bug do conteúdo.