Convert integer to hexadecimal and back again

前端 未结 10 2160
轮回少年
轮回少年 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:33

    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;
            }
        }
    
    0 讨论(0)
  • 2020-11-22 02:35

    int to hex:

    int a = 72;

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

    hex to int:

    int b = 0xB76;

    Console.WriteLine(b);

    0 讨论(0)
  • 2020-11-22 02:37
    int valInt = 12;
    Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
    Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output
    
    0 讨论(0)
  • 2020-11-22 02:38

    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.

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

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

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

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

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

    To Hex:

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

    To int:

    int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
    
    0 讨论(0)
提交回复
热议问题