2008-09-16 25 views

Répondre

233

Pour convertir de décimal en hex faire ...

string hexValue = decValue.ToString("X"); 

Pour convertir d'hexagone en décimal ne soit ...

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); 

ou

int decValue = Convert.ToInt32(hexValue, 16); 
+1

Je voudrais comprendre comment cette ligne decValue.ToString ("X") le convertit en hexadécimal. – gizgok

+20

La variable decValue est de type Int32. Int32 a une surcharge ToString() qui peut accepter un parmi un certain nombre de chaînes de format qui dictent comment la valeur sera représentée comme une chaîne. La chaîne de format "X" signifie Hexidecimal donc 255.ToString ("X") retournera la chaîne hexadécimale "FF". Pour plus d'informations, voir http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx –

+2

Convert.ToInt32 a de meilleures performances que int.Parse (...) –

1
String stringrep = myintvar.ToString("X"); 

int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber); 
22

Il semble que vous pouvez dire

Convert.ToInt64(value, 16) 

pour obtenir la décimale de hexdecimal.

L'inverse est:

otherVar.ToString("X"); 
+0

Je reçois System.FormatException: Le format spécifié 'x' est invalide –

2

From Geekpedia:

// Store integer 182 
int decValue = 182; 

// Convert integer 182 as a hex in a string variable 
string hexValue = decValue.ToString("X"); 

// Convert the hex string back to the number 
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); 
47

Hex -> décimales:

Convert.ToInt64(hexValue, 16); 

décimal -> Hex

string.format("{0:x}", decValue); 
+4

+1 la bonne chose à propos 'Convert.ToInt64 (hexValue, 16);' est qu'il fera la conversion si le '0x' préfixe est là ou non, alors que certaines autres solutions ne le seront pas. – Craig

+0

@Craig salut, donc je dois faire la conversion basée sur la taille hexadécimale ou je peux appliquer ToInt64 pour toute la valeur hexadécimale, y aura-t-il un impact? – user1219310

3
static string chex(byte e)     // Convert a byte to a string representing that byte in hexadecimal 
    { 
     string r = ""; 
     string chars = "ABCDEF"; 
     r += chars[e >> 4]; 
     return r += chars[e &= 0x0F]; 
    }   // Easy enough... 

    static byte CRAZY_BYTE(string t, int i)  // Take a byte, if zero return zero, else throw exception (i=0 means false, i>0 means true) 
    { 
     if (i == 0) return 0; 
     throw new Exception(t); 
    } 

    static byte hbyte(string e)     // Take 2 characters: these are hex chars, convert it to a byte 
    {           // WARNING: This code will make small children cry. Rated R. 
     e = e.ToUpper(); // 
     string msg = "INVALID CHARS";   // The message that will be thrown if the hex str is invalid 

     byte[] t = new byte[]     // Gets the 2 characters and puts them in seperate entries in a byte array. 
     {          // This will throw an exception if (e.Length != 2). 
      (byte)e[CRAZY_BYTE("INVALID LENGTH", e.Length^0x02)], 
      (byte)e[0x01] 
     }; 

     for (byte i = 0x00; i < 0x02; i++)  // Convert those [ascii] characters to [hexadecimal] characters. Error out if either character is invalid. 
     { 
      t[i] -= (byte)((t[i] >= 0x30) ? 0x30 : CRAZY_BYTE(msg, 0x01));         // Check for 0-9 
      t[i] -= (byte)((!(t[i] < 0x0A)) ? (t[i] >= 0x11 ? 0x07 : CRAZY_BYTE(msg, 0x01)) : 0x00);  // Check for A-F 
     }   

     return t[0x01] |= t[0x00] <<= 0x04;  // The moment of truth. 
    } 
2

Cette n'est pas vraiment le moyen le plus simple mais ce code source vous permet de corriger tous les types de nombre octal 23.214, 23 et 0.512 et ainsi de suite. Espérons que cela vous aidera ..

public string octal_to_decimal(string m_value) 
    { 
     double i, j, x = 0; 
     Int64 main_value; 
     int k = 0; 
     bool pw = true, ch; 
     int position_pt = m_value.IndexOf("."); 
     if (position_pt == -1) 
     { 
      main_value = Convert.ToInt64(m_value); 
      ch = false; 
     } 
     else 
     { 
      main_value = Convert.ToInt64(m_value.Remove(position_pt, m_value.Length - position_pt)); 
      ch = true; 
     } 

     while (k <= 1) 
     { 
      do 
      { 
       i = main_value % 10;          // Return Remainder 
       i = i * Convert.ToDouble(Math.Pow(8, x));     // calculate power 
       if (pw) 
        x++; 
       else 
        x--; 
       o_to_d = o_to_d + i;          // Saving Required calculated value in main variable 
       main_value = main_value/10;        // Dividing the main value 
      } 
      while (main_value >= 1); 
      if (ch) 
      { 
       k++; 
       main_value = Convert.ToInt64(Reversestring(m_value.Remove(0, position_pt + 1))); 
      } 
      else 
       k = 2; 
      pw = false; 
      x = -1; 
     } 
     return (Convert.ToString(o_to_d)); 
    }  
+1

Bienvenue sur stackoverflow. Pourriez-vous s'il vous plaît expliquer un peu votre code (mybe juste une courte phrase). Merci! –

0

Si c'est une chaîne hexagonale vraiment grand au-delà de la capacité de l'entier normal:

Pour .NET 3.5, nous pouvons utiliser la classe BigInteger de BouncyCastle:

String hex = "68c7b05d0000000002f8"; 
// results in "494809724602834812404472" 
String decimal = new Org.BouncyCastle.Math.BigInteger(hex, 16).ToString(); 

.NET 4.0 a la classe BigInteger.

-1

Une méthode d'extension pour convertir un tableau d'octets en une représentation hexadécimale. Cela remplit chaque octet avec des zéros en tête.

/// <summary> 
    /// Turns the byte array into its Hex representation. 
    /// </summary> 
    public static string ToHex(this byte[] y) 
    { 
     StringBuilder sb = new StringBuilder(); 
     foreach (byte b in y) 
     { 
      sb.Append(b.ToString("X").PadLeft(2, "0"[0])); 
     } 
     return sb.ToString(); 
    } 
11

Si vous voulez des performances maximales Lors de la conversion d'hexagone en nombre décimal, vous pouvez utiliser l'approche avec table pré-remplie de valeurs décimales à six pans.

Voici le code qui illustre cette idée. Mon performance tests a montré qu'il peut être 20% à 40% plus rapide que Convert.ToInt32 (...):

class TableConvert 
    { 
     static sbyte[] unhex_table = 
     { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 
     ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 
     ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 
     , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 
     ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 
     ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 
     ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 
     ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 
     }; 

     public static int Convert(string hexNumber) 
     { 
      int decValue = unhex_table[(byte)hexNumber[0]]; 
      for (int i = 1; i < hexNumber.Length; i++) 
      { 
       decValue *= 16; 
       decValue += unhex_table[(byte)hexNumber[i]]; 
      } 
      return decValue; 
     } 
    } 
+0

Approche intéressante –

+0

Genius! Je me demande s'il est possible que le compilateur d'octets utilise automatiquement cette approche dans le Convert.ToInt32? –

+1

Je ne vois aucune raison pour laquelle cela ne peut pas être fait. Toutefois, la conservation de la matrice consommera de la mémoire supplémentaire. –

0

Voici ma fonction:

using System; 
using System.Collections.Generic; 
class HexadecimalToDecimal 
{ 
    static Dictionary<char, int> hexdecval = new Dictionary<char, int>{ 
     {'0', 0}, 
     {'1', 1}, 
     {'2', 2}, 
     {'3', 3}, 
     {'4', 4}, 
     {'5', 5}, 
     {'6', 6}, 
     {'7', 7}, 
     {'8', 8}, 
     {'9', 9}, 
     {'a', 10}, 
     {'b', 11}, 
     {'c', 12}, 
     {'d', 13}, 
     {'e', 14}, 
     {'f', 15}, 
    }; 

    static decimal HexToDec(string hex) 
    { 
     decimal result = 0; 
     hex = hex.ToLower(); 

     for (int i = 0; i < hex.Length; i++) 
     { 
      char valAt = hex[hex.Length - 1 - i]; 
      result += hexdecval[valAt] * (int)Math.Pow(16, i); 
     } 

     return result; 
    } 

    static void Main() 
    { 

     Console.WriteLine("Enter Hexadecimal value"); 
     string hex = Console.ReadLine().Trim(); 

     //string hex = "29A"; 
     Console.WriteLine("Hex {0} is dec {1}", hex, HexToDec(hex)); 

     Console.ReadKey(); 
    } 
} 
+0

Cela pourrait être un bon candidat pour une méthode d'extension ** 'Convert' ** afin que l'on puisse écrire:' int hexa = Convert.ToHexadecimal (11); '=) –

0

Ma version est je pense un peu plus compréhensible parce que ma connaissance C# n'est pas si élevée. J'utilise cet algorithme: http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal (l'exemple 2)

using System; 
using System.Collections.Generic; 

static class Tool 
{ 
    public static string DecToHex(int x) 
    { 
     string result = ""; 

     while (x != 0) 
     { 
      if ((x % 16) < 10) 
       result = x % 16 + result; 
      else 
      { 
       string temp = ""; 

       switch (x % 16) 
       { 
        case 10: temp = "A"; break; 
        case 11: temp = "B"; break; 
        case 12: temp = "C"; break; 
        case 13: temp = "D"; break; 
        case 14: temp = "E"; break; 
        case 15: temp = "F"; break; 
       } 

       result = temp + result; 
      } 

      x /= 16; 
     } 

     return result; 
    } 

    public static int HexToDec(string x) 
    { 
     int result = 0; 
     int count = x.Length - 1; 
     for (int i = 0; i < x.Length; i++) 
     { 
      int temp = 0; 
      switch (x[i]) 
      { 
       case 'A': temp = 10; break; 
       case 'B': temp = 11; break; 
       case 'C': temp = 12; break; 
       case 'D': temp = 13; break; 
       case 'E': temp = 14; break; 
       case 'F': temp = 15; break; 
       default: temp = -48 + (int)x[i]; break; // -48 because of ASCII 
      } 

      result += temp * (int)(Math.Pow(16, count)); 
      count--; 
     } 

     return result; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.Write("Enter Decimal value: "); 
     int decNum = int.Parse(Console.ReadLine()); 

     Console.WriteLine("Dec {0} is hex {1}", decNum, Tool.DecToHex(decNum)); 

     Console.Write("\nEnter Hexadecimal value: "); 
     string hexNum = Console.ReadLine().ToUpper(); 

     Console.WriteLine("Hex {0} is dec {1}", hexNum, Tool.HexToDec(hexNum)); 

     Console.ReadKey(); 
    } 
} 
0

binaire Convertir Hex

Convert.ToString(Convert.ToUInt32(binary1, 2), 16).ToUpper() 
2

Hex Décimal Conversion

Convert.ToInt32(number, 16); 

décimal Hex Conversion

int.Parse(number, System.Globalization.NumberStyles.HexNumber) 

For more details Check this article

+0

Cela semble être juste une répétition de [cette réponse ] (https://stackoverflow.com/a/74223). – Pang