554

How can I convert the following?

2934 (integer) to B76 (hex)

Let me explain what I am trying to do. I have User IDs in my database that are stored as integers. Rather than having users reference their IDs I want to let them use the hex value. The main reason is because it's shorter.

So not only do I need to go from integer to hex but I also need to go from hex to integer.

Is there an easy way to do this in C#?

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
codette
  • 12,343
  • 9
  • 37
  • 38
  • 1
    You have a good point. But we're trying to convert the integer ID into something that takes up fewer characters. Thanks for the insight tho. – codette Jul 16 '09 at 20:24
  • 1
    @codette Storing numbers as numbers will take up the least space while still readable. For example, 4 bytes for numbers up to 2bln (integer). Or if it's too long for any numeric type, use a binary field. – Luc Jan 25 '13 at 12:30
  • 9
    @Luc The OP states _I have User IDs in my database that are stored as integers. Rather than having users reference their IDs I want to let them use the hex value._ so codette is storing the values as an int, but converting to/from hex for the user. – Trisped Apr 04 '13 at 18:00
  • A fashionably belated response, but have you considered some sort of `Integer` shortening implementation? If the only goal is to make the user ID as short as possible, I'd be interested to know if there is any other apparent reason why you specifically require hexadecimal conversion - unless I missed it of course. Is it clear and known (if so required) that user IDs are in actual fact a hexadecimal representation of the real value? – WynandB Oct 17 '10 at 06:49

12 Answers12

983
// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

from http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html


HINT (from the comments):

Use .ToString("X4") to get exactly 4 digits with leading 0, or .ToString("x4") for lowercase hex numbers (likewise for more digits).

Matt
  • 25,467
  • 18
  • 120
  • 187
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
  • 197
    you can also specify the number of digits by using: decValue.ToString("X4") – Martin Oct 27 '09 at 09:04
  • 91
    Since this has not been mentioned here: If you use a lowecase x (e.g. ToString("x4) you get a lowercase hex value (e.g. b76). – Skalli Feb 28 '14 at 09:17
  • 14
    Am I the only one having a hard time tolerating the variable name "decValue" since it is not a decimal at all? Sorry man, I know it is from another source, but stackoverflow should be better than that. – Christopher Bonitz Nov 03 '15 at 10:24
  • 8
    @bonitzenator lol, in the 6 years this answer has existed, I've never noticed that. Updated! – Gavin Miller Nov 03 '15 at 15:07
  • 1
    Note that your hex to int solution will produce SIGNED integers and maxes out at 8 hex chars. – Scott Solmer Mar 08 '16 at 19:24
  • 1
    FTR; `decValue` is arguably better than `intValue` because an integer can be expressed in either decimal notation or hexadecimal notation. `intValue` is technically more ambiguous, as `decValue` indicates clearly (in this context) that you're working with the decimal representation rather than the hexadecimal. Just my 2A¢. – Dan Lugg Aug 24 '17 at 05:05
  • This seems to have problems with specific colors such as #00FFFF – Lord Darth Vader Dec 05 '17 at 08:54
  • @R2D2 that's because this code isn't written to support colors. It's not RGB to Hex. It's integer to hex. – Gavin Miller Dec 05 '17 at 12:45
  • If you need tryparse: Int32.TryParse(hexValue, System.Globalization.NumberStyles.HexNumber, Globalization.CultureInfo.InvariantCulture, intValue) – VoteCoffee Apr 28 '18 at 19:14
  • @DanLugg The base that's used to represent the value only applies when the value is converted to a string. While we're used to seeing integers represented in decimal, remember that internally they're represented in binary. – Kyle Delaney Jul 06 '18 at 15:58
  • HINT: Use `.ToString("X4")` to get exactly 4 digits with leading 0, or `.ToString("x4")` for lowercase hex numbers. – Matt Nov 12 '21 at 11:18
122

Use:

int myInt = 2934;
string myHex = myInt.ToString("X");  // Gives you hexadecimal
int myNewInt = Convert.ToInt32(myHex, 16);  // Back to int again.

See How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide) for more information and examples.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Scott Ivey
  • 40,768
  • 21
  • 80
  • 118
68

Try the following to convert it to hex

public static string ToHex(this int value) {
  return String.Format("0x{0:X}", value);
}

And back again

public static int FromHex(string value) {
  // strip the leading 0x
  if ( value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) {
    value = value.Substring(2);
  }
  return Int32.Parse(value, NumberStyles.HexNumber);
}
s d
  • 2,666
  • 4
  • 26
  • 42
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 9
    or the "0x" bit, which is something the OP didn't really want – Philippe Leybaert Jul 16 '09 at 20:11
  • Well, it didn't really answer the OP's question. In fact, the code you presented didn't work for the OP's problem. I rarely downvote, but if I do, I always make a comment and check back to see if the answer was edited, and in many cases I remove the downvote again. No offense. – Philippe Leybaert Jul 16 '09 at 20:18
  • 8
    (I'm already sorry I commented). The question was "how do I convert 2934 to B76". Other answers did indeed only provide half of the solution, but your's converted "2934" to "0xB76". It's not a bad solution at all, but it's not an answer to the question that was asked. – Philippe Leybaert Jul 16 '09 at 20:31
35
int valInt = 12;
Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output
Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
user2179382
  • 351
  • 3
  • 3
19
string HexFromID(int ID)
{
    return ID.ToString("X");
}

int IDFromHex(string HexID)
{
    return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
}

I really question the value of this, though. You're stated goal is to make the value shorter, which it will, but that isn't a goal in itself. You really mean either make it easier to remember or easier to type.

If you mean easier to remember, then you're taking a step backwards. We know it's still the same size, just encoded differently. But your users won't know that the letters are restricted to 'A-F', and so the ID will occupy the same conceptual space for them as if the letter 'A-Z' were allowed. So instead of being like memorizing a telephone number, it's more like memorizing a GUID (of equivalent length).

If you mean typing, instead of being able to use the keypad the user now must use the main part of the keyboard. It's likely to be more difficult to type, because it won't be a word their fingers recognize.

A much better option is to actually let them pick a real username.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • The goal really is to take up fewer characters. Take twitter for example where they only allow 140 character messages. We're doing something similar so we're trying to give our users a way of shortening their user ID. – codette Jul 16 '09 at 20:41
  • 3
    In that case, you should think about a binary representation. This is likely a 32bit int that just doesn't use the negative portion, meaning 16bits of resolution. You can put that in one unicode character pretty easily. – Joel Coehoorn Jul 16 '09 at 21:14
  • 5
    Belated response, but - a 32 bit (signed) int that never contains negative numbers has 31 bits of resolution, not 16. You might be able to stuff that into one unicode character, but when it's UTF8 encoded, unless it's between 0 and 127 it's going to take up more characters than the hex equivalent. HEX is not a terrible solution for this problem, but a base64 of the four bytes in the int would be even shorter (and you could trim the padding) – James Hart Aug 16 '11 at 21:08
  • Yeah, I had a brain-fart right there. I wish I could edit a comment. – Joel Coehoorn Oct 31 '14 at 20:12
15

To Hex:

string hex = intValue.ToString("X");

To int:

int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
Brandon
  • 68,708
  • 30
  • 194
  • 223
9

I created my own solution for converting int to Hex string and back before I found this answer. Not surprisingly, it's considerably faster than the .net solution since there's less code overhead.

        /// <summary>
        /// Convert an integer to a string of hexidecimal numbers.
        /// </summary>
        /// <param name="n">The int to convert to Hex representation</param>
        /// <param name="len">number of digits in the hex string. Pads with leading zeros.</param>
        /// <returns></returns>
        private static String IntToHexString(int n, int len)
        {
            char[] ch = new char[len--];
            for (int i = len; i >= 0; i--)
            {
                ch[len - i] = ByteToHexChar((byte)((uint)(n >> 4 * i) & 15));
            }
            return new String(ch);
        }

        /// <summary>
        /// Convert a byte to a hexidecimal char
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private static char ByteToHexChar(byte b)
        {
            if (b < 0 || b > 15)
                throw new Exception("IntToHexChar: input out of range for Hex value");
            return b < 10 ? (char)(b + 48) : (char)(b + 55);
        }

        /// <summary>
        /// Convert a hexidecimal string to an base 10 integer
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static int HexStringToInt(String str)
        {
            int value = 0;
            for (int i = 0; i < str.Length; i++)
            {
                value += HexCharToInt(str[i]) << ((str.Length - 1 - i) * 4);
            }
            return value;
        }

        /// <summary>
        /// Convert a hex char to it an integer.
        /// </summary>
        /// <param name="ch"></param>
        /// <returns></returns>
        private static int HexCharToInt(char ch)
        {
            if (ch < 48 || (ch > 57 && ch < 65) || ch > 70)
                throw new Exception("HexCharToInt: input out of range for Hex value");
            return (ch < 58) ? ch - 48 : ch - 55;
        }

Timing code:

static void Main(string[] args)
        {
            int num = 3500;
            long start = System.Diagnostics.Stopwatch.GetTimestamp();
            for (int i = 0; i < 2000000; i++)
                if (num != HexStringToInt(IntToHexString(num, 3)))
                    Console.WriteLine(num + " = " + HexStringToInt(IntToHexString(num, 3)));
            long end = System.Diagnostics.Stopwatch.GetTimestamp();
            Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);

            for (int i = 0; i < 2000000; i++)
                if (num != Convert.ToInt32(num.ToString("X3"), 16))
                    Console.WriteLine(i);
            end = System.Diagnostics.Stopwatch.GetTimestamp();
            Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);
            Console.ReadLine(); 
        }

Results:

Digits : MyCode : .Net
1 : 0.21 : 0.45
2 : 0.31 : 0.56
4 : 0.51 : 0.78
6 : 0.70 : 1.02
8 : 0.90 : 1.25
Eric Helms
  • 91
  • 1
  • 1
2

NET FRAMEWORK

Very well explained and few programming lines GOOD JOB

// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

PASCAL >> C#

http://files.hddguru.com/download/Software/Seagate/St_mem.pas

Something from the old school very old procedure of pascal converted to C #

    /// <summary>
    /// Conver number from Decadic to Hexadecimal
    /// </summary>
    /// <param name="w"></param>
    /// <returns></returns>
    public string MakeHex(int w)
    {
        try
        {
           char[] b =  {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
           char[] S = new char[7];

              S[0] = b[(w >> 24) & 15];
              S[1] = b[(w >> 20) & 15];
              S[2] = b[(w >> 16) & 15];
              S[3] = b[(w >> 12) & 15];
              S[4] = b[(w >> 8) & 15];
              S[5] = b[(w >> 4) & 15];
              S[6] = b[w & 15];

              string _MakeHex = new string(S, 0, S.Count());

              return _MakeHex;
        }
        catch (Exception ex)
        {

            throw;
        }
    }
Spektre
  • 49,595
  • 11
  • 110
  • 380
JAAR
  • 31
  • 2
  • 2
    Thank you for reply. If possible please translate to English as best you can. Don't worry about any possible grammar mistakes, we will correct them. – bcperth Oct 11 '18 at 22:50
1

Print integer in hex-value with zero-padding (if needed) :

int intValue = 1234;

Console.WriteLine("{0,0:D4} {0,0:X3}", intValue); 

https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros

Blue
  • 22,608
  • 7
  • 62
  • 92
Siva
  • 21
  • 1
  • 5
1

Like @Joel C, I think this is an AB problem. There’s an existing algorithm that I think suits the need as described better which is uuencode, which I’m sure has many public domain implementations, perhaps tweaked to eliminate characters that looks very similar like 0/O. Likely to produce significantly shorter strings. I think this is what URL shorteners use.

  • I wonder if my answer is worth improving by finding such code or if it’s a dead end. Thoughts? (I was horrified to discover that Apple code stores and processes a vast amount of hex data as ASCII. https://developer.apple.com/forums/thread/667524) – WHO'sNoToOldRx4Covid-CENSORED Dec 02 '21 at 20:52
0

This was an answer to a homework problem from long ago .. like when there were still only 3 Star Wars movies. I am sure it is not perfect. It seems we were more interested in algorithms. I added some stuff to main to see if returns what the standard functions do. Need a reverse string function .. easy peasy. Call it from the command line "./a.out 123" etc. Trust but verify, of course. Best

char* decToBase(int n,const int base)
{
    char hexb[] = "0123456789abcdef";
    int i=0;

    char* s = new char[BSIZE];

    while(n)
    {
        s[i++] = hexb[n % base];
        n = n / base;
    }
    rev_string(s);

    return s;
}

int main(int argc, char* argv[])
{
    int num = atoi(argv[argc-1]);
    char* str = decToBase(num,2);
    cout << str << " " << std::bitset<32>(num).to_string() << '\n';
    cout << decToBase(num,8) << " " << oct << num << '\n';
    cout << decToBase(num,16) << " " << hex << num << '\n';
    delete[] str;

    return 0;
}
-5

int to hex:

int a = 72;

Console.WriteLine("{0:X}", a);

hex to int:

int b = 0xB76;

Console.WriteLine(b);

Community
  • 1
  • 1
novice
  • 1
  • 1