Convert integer to hexadecimal and back again

前端 未结 10 2175
轮回少年
轮回少年 2020-11-22 02:33

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 inte

相关标签:
10条回答
  • 2020-11-22 02:47

    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
    
    0 讨论(0)
  • 2020-11-22 02:49
    // 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

    0 讨论(0)
  • 2020-11-22 02:49
    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.

    0 讨论(0)
  • 2020-11-22 02:58

    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);
    }
    
    0 讨论(0)
提交回复
热议问题