हेक्साडेसिमल और दशमलव के बीच संख्याओं को कैसे परिवर्तित करें


जवाबों:


281

दशमलव से हेक्स में परिवर्तित करने के लिए ...

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

हेक्स से दशमलव में बदलने के लिए या तो ...

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

या

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

1
मैं यह समझना चाहूंगा कि यह रेखा कैसे विचलित होती है। TString ("X") इसे हेक्स में परिवर्तित करता है।
गिज़गोक

20
चर decValue Int32 प्रकार का है। Int32 में एक ToString () अधिभार है जो कई प्रकार के प्रारूप स्ट्रिंग्स में से एक को स्वीकार कर सकता है जो यह निर्धारित करता है कि कैसे मूल्य को एक स्ट्रिंग के रूप में दर्शाया जाएगा। "X" प्रारूप स्ट्रिंग का अर्थ है हेक्सिडेसिमल 255. तोस्ट्रिंग ("X") हेक्साडेसिमल स्ट्रिंग "FF" लौटाएगा। अधिक जानकारी के लिए देखें msdn.microsoft.com/en-us/library/dwhawy9k.aspx
एंडी मैक्लोड

2
अच्छा उत्तर। मैं वास्तव में int.TryParse का उपयोग कर रहा हूँ बजाय int.Parse के लिए कष्टप्रद कोशिश पकड़ने ब्लॉक का उपयोग करने से बचने के लिए।
ROFLwTIME

9
@VadymStetsiak Convert.ToInt32 सिर्फ Int32.Parse (int.Parse) (चेहरे की हथेली) को कॉल करता है
कोल जॉनसन

@ColeJohnson के int.Parseपास आपके लिए विकल्प नहीं है कि वह आधार को intकेवल कुछ मान्य में से एक के रूप में निर्दिष्ट कर सके NumberStyles। बेस 16 के लिए, या तो बस ठीक है, लेकिन एक सामान्य समाधान के रूप में, यह जानना अच्छा है कि दोनों कैसे काम करते हैं।
टिम एस।

54

हेक्स -> दशमलव:

Convert.ToInt64(hexValue, 16);

दशमलव -> हेक्स

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

6
+1 के बारे में अच्छी बात Convert.ToInt64(hexValue, 16);यह है कि यह रूपांतरण करेगा यदि 0xउपसर्ग है या नहीं, जबकि, कुछ अन्य समाधान नहीं होंगे।
क्रेग

@ क्रेग हाय, इसलिए मुझे हेक्स मान के आकार के आधार पर रूपांतरण करने की आवश्यकता है या मैं सभी हेक्स मान के लिए TOInt64 लागू कर सकता हूं, क्या कोई प्रभाव पड़ेगा?
user1219310

26

ऐसा लगता है कि आप कह सकते हैं

Convert.ToInt64(value, 16)

हेक्साडेसिमल से दशमलव प्राप्त करने के लिए।

आसपास का दूसरा तरीका है:

otherVar.ToString("X");

मुझे System.FormatException मिलता है: निर्दिष्ट प्रारूप 'x' अमान्य है
c_Reg_c_Lark

13

यदि आप हेक्स से दशमलव संख्या में रूपांतरण करते समय अधिकतम प्रदर्शन चाहते हैं, तो आप हेक्स-टू-दशमलव मूल्यों की पूर्व-आबादी वाली तालिका के साथ दृष्टिकोण का उपयोग कर सकते हैं।

यहां वह कोड है जो उस विचार को दिखाता है। मेरे प्रदर्शन परीक्षणों से पता चला कि यह Convert.ToInt32 (...) से 20% -40% तेज हो सकता है:

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;
      }
  }

प्रतिभाशाली! आश्चर्य है कि बाइट संकलक को स्वचालित रूप से Convert.ToInt32 के अंदर इस दृष्टिकोण का उपयोग करना संभव है?
जेफ हैलवरसन

1
मुझे ऐसा कोई कारण नहीं दिखता है कि ऐसा क्यों नहीं किया जा सकता है। हालांकि, सरणी बनाए रखने से अतिरिक्त मेमोरी की खपत होगी।
वडियम स्टेशियाक

8

गीकपेडिया से :

// 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);

मैंने कुछ ही मिनटों में छोटे डॉटनेट 4.0 ऐप बनाने के लिए इस पद्धति का उपयोग किया, कोड की कुछ पंक्तियों के साथ बढ़िया काम करता है।
RatherLogical

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

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


1
    static string chex(byte e)                  // Convert a byte to a string representing that byte in hexadecimal
    {
        string r = "";
        string chars = "0123456789ABCDEF";
        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.
    }

1

यह वास्तव में सबसे आसान तरीका नहीं है, लेकिन यह स्रोत कोड आपको किसी भी प्रकार के अष्टक संख्या यानी 23.214, 23 और 0.512 को सही करने में सक्षम करता है। आशा है कि यह आपकी मदद करेगा..

    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));
    }    

2
स्टैकओवरफ़्लो पर आपका स्वागत है। क्या आप कृपया अपने कोड को थोड़ा समझा सकते हैं। धन्यवाद!
डेनियल बी

1

C # में BigNumber का उपयोग करने का प्रयास करें - एक बड़े पैमाने पर हस्ताक्षरित पूर्णांक का प्रतिनिधित्व करता है।

कार्यक्रम

using System.Numerics;
...
var bigNumber = BigInteger.Parse("837593454735734579347547357233757342857087879423437472347757234945743");
Console.WriteLine(bigNumber.ToString("X"));

उत्पादन

4F30DC39A5B10A824134D5B18EEA3707AC854EE565414ED2E498DCFDE1A15DA5FEB6074AE248458435BD417F06F674EB29A2CFECF

संभावित अपवाद,

ArgumentNullException - मान शून्य है।

FormatException - मान सही प्रारूप में नहीं है।

निष्कर्ष

आप स्ट्रिंग को कनवर्ट कर सकते हैं और BigNumber में एक मान को स्टोर कर सकते हैं, जब तक कि स्ट्रिंग खाली न हो और गैर-विश्लेषक न हों


0

यदि यह सामान्य पूर्णांक की क्षमता से परे एक बहुत बड़ी हेक्स स्ट्रिंग है:

.NET 3.5 के लिए, हम BouncyCastle के BigInteger वर्ग का उपयोग कर सकते हैं:

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

.NET 4.0 में BigInteger वर्ग है।


0

मेरा संस्करण मुझे लगता है कि थोड़ा और अधिक समझने योग्य है क्योंकि मेरा सी # ज्ञान इतना अधिक नहीं है। मैं इस एल्गोरिथ्म का उपयोग कर रहा हूं: http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal (उदाहरण 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

बाइनरी को हेक्स में बदलें

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

-1

एक बाइट सरणी में हेक्स प्रतिनिधित्व में परिवर्तित करने के लिए एक विस्तार विधि। यह प्रमुख जीरो के साथ प्रत्येक बाइट को पैड करता है।

    /// <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();
    }

-1

यहाँ मेरा कार्य है:

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();
    }
}

यह एक Convertविस्तार पद्धति के लिए एक अच्छा उम्मीदवार हो सकता है ताकि कोई लिख सके: int hexa = Convert.ToHexadecimal(11);=)
मार्क मार्किलर

-1

मेरा समाधान मूल बातें करने के लिए थोड़ा सा है, लेकिन यह बिना किसी अंतर्निहित कार्यों का उपयोग किए बिना संख्या प्रणालियों के बीच परिवर्तित करने के लिए काम करता है।

    public static string DecToHex(long a)
    {
        int n = 1;
        long b = a;
        while (b > 15)
        {
            b /= 16;
            n++;
        }
        string[] t = new string[n];
        int i = 0, j = n - 1;
        do
        {
                 if (a % 16 == 10) t[i] = "A";
            else if (a % 16 == 11) t[i] = "B";
            else if (a % 16 == 12) t[i] = "C";
            else if (a % 16 == 13) t[i] = "D";
            else if (a % 16 == 14) t[i] = "E";
            else if (a % 16 == 15) t[i] = "F";
            else t[i] = (a % 16).ToString();
            a /= 16;
            i++;
        }
        while ((a * 16) > 15);
        string[] r = new string[n];
        for (i = 0; i < n; i++)
        {
            r[i] = t[j];
            j--;
        }
        string res = string.Concat(r);
        return res;
    }

-1
class HexToDecimal
{
    static void Main()
    {
        while (true)
        {
            Console.Write("Enter digit number to convert: ");
            int n = int.Parse(Console.ReadLine()); // set hexadecimal digit number  
            Console.Write("Enter hexadecimal number: ");
            string str = Console.ReadLine();
            str.Reverse();

            char[] ch = str.ToCharArray();
            int[] intarray = new int[n];

            decimal decimalval = 0;

            for (int i = ch.Length - 1; i >= 0; i--)
            {
                if (ch[i] == '0')
                    intarray[i] = 0;
                if (ch[i] == '1')
                    intarray[i] = 1;
                if (ch[i] == '2')
                    intarray[i] = 2;
                if (ch[i] == '3')
                    intarray[i] = 3;
                if (ch[i] == '4')
                    intarray[i] = 4;
                if (ch[i] == '5')
                    intarray[i] = 5;
                if (ch[i] == '6')
                    intarray[i] = 6;
                if (ch[i] == '7')
                    intarray[i] = 7;
                if (ch[i] == '8')
                    intarray[i] = 8;
                if (ch[i] == '9')
                    intarray[i] = 9;
                if (ch[i] == 'A')
                    intarray[i] = 10;
                if (ch[i] == 'B')
                    intarray[i] = 11;
                if (ch[i] == 'C')
                    intarray[i] = 12;
                if (ch[i] == 'D')
                    intarray[i] = 13;
                if (ch[i] == 'E')
                    intarray[i] = 14;
                if (ch[i] == 'F')
                    intarray[i] = 15;

                decimalval += intarray[i] * (decimal)Math.Pow(16, ch.Length - 1 - i);

            }

            Console.WriteLine(decimalval);
        }

    }

}
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.