Konwertuj liczbę całkowitą na szesnastkową i z powrotem

Jak mogę przekonwertować następujące elementy?

2934 (liczba całkowita) do B76 (hex)

Pozwól mi wyjaśnić, co próbuję zrobić. W mojej bazie danych mam identyfikatory użytkowników, które są przechowywane jako liczby całkowite. Zamiast odwoływać się do swoich identyfikatorów, chcę pozwolić im używać wartości szesnastkowej. Głównym powodem jest to, że jest krótszy.

Więc nie tylko muszę przejść z liczby całkowitej do liczby szesnastkowej, ale także muszę przejść z liczby szesnastkowej do liczby całkowitej.

Czy jest łatwy sposób na to w C#?

Author: Glenn Ferrie, 2009-07-16

10 answers

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

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

 892
Author: Gavin Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-03 15:07:30

Użycie:

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

Zobacz Jak: konwertować między Szesnastkowymi ciągami znaków i typami liczbowymi (C# Programming Guide) Więcej informacji i przykłady.

 115
Author: Scott Ivey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-09 22:21:00

Spróbuj przekonwertować go na hex

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

I z powrotem

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);
}
 62
Author: JaredPar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-13 00:45:26
int valInt = 12;
Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output
 27
Author: user2179382,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-11 03:48:31
string HexFromID(int ID)
{
    return ID.ToString("X");
}

int IDFromHex(string HexID)
{
    return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
}
Naprawdę kwestionuję wartość tego. Jesteś stwierdził, że celem jest, aby wartość krótsza, co będzie, ale to nie jest cel sam w sobie. Masz na myśli albo łatwiej zapamiętać, albo łatwiej pisać. Jeśli masz na myśli łatwiej zapamiętać, to robisz krok do tyłu. Wiemy, że to wciąż ten sam rozmiar, tylko zakodowany inaczej. Ale twoi użytkownicy nie będą wiedzieli, że litery są ograniczone do 'A-F' , więc IDENTYFIKATOR będzie zajmował dla nich tę samą przestrzeń koncepcyjną tak, jakby dozwolone były litery "A-Z". Zamiast więc przypominać zapamiętywanie numeru telefonu, jest to bardziej zapamiętywanie identyfikatora GUID (o równoważnej długości).

Jeśli masz na myśli pisanie, zamiast używać klawiatury, użytkownik musi teraz użyć głównej części klawiatury. Prawdopodobnie będzie trudniej pisać, ponieważ nie będzie to słowo, które rozpoznają ich palce.

O wiele lepszą opcją jest umożliwienie im wybrania prawdziwej nazwy użytkownika.

 19
Author: Joel Coehoorn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-17 21:05:01

Do Hex:

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

Do int:

int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)
 15
Author: Brandon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-16 20:07:40

Stworzyłem własne rozwiązanie do konwersji int na ciąg Hex i z powrotem, zanim znalazłem tę odpowiedź. Nic dziwnego, że jest znacznie szybszy niż rozwiązanie. NET, ponieważ jest mniej narzutu kodu.

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

Kod czasu:

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

Wyniki:

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
 7
Author: Eric Helms,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-24 11:56:33

NET FRAMEWORK

Bardzo dobrze wyjaśnione i kilka linii programowania DOBRA ROBOTA

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

Coś ze starej szkoły bardzo stara procedura Pascala konwertowana do 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;
        }
    }
 2
Author: JAAR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-18 15:27:18

Wypisuje liczbę całkowitą w wartości szesnastkowej z wypełnieniem zerowym (w razie potrzeby):

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

 1
Author: Siva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-06 21:31:41

Int to hex:

Int a = 72;

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

Hex do int:

Int b = 0xb76;

Konsola.WriteLine (b);

 -6
Author: novice,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55