[C#] 정수를 16 진수로 변환 한 후 다시 변환

다음을 어떻게 변환 할 수 있습니까?

2934 (정수)-B76 (16 진)

내가하려는 일을 설명하겠습니다. 데이터베이스에 정수로 저장된 사용자 ID가 있습니다. 사용자가 자신의 ID를 참조하도록하는 대신 16 진수 값을 사용하도록하고 싶습니다. 주된 이유는 더 짧기 때문입니다.

따라서 정수에서 16 진수로 이동해야 할뿐만 아니라 16 진수에서 정수로 이동해야합니다.

C #에서 이것을 수행하는 쉬운 방법이 있습니까?



답변

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

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


답변

사용하다:

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

자세한 내용과 예제는 방법 : 16 진수 문자열과 숫자 형식 간 변환 (C # 프로그래밍 안내서) 을 참조하십시오.


답변

16 진수로 변환하려면 다음을 시도하십시오

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

그리고 다시

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


답변

int valInt = 12;
Console.WriteLine(valInt.ToString("X"));  // C  ~ possibly single-digit output 
Console.WriteLine(valInt.ToString("X2")); // 0C ~ always double-digit output


답변

string HexFromID(int ID)
{
    return ID.ToString("X");
}

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

그래도 나는 이것의 가치에 의문을 갖는다. 목표는 가치를 더 짧게 만드는 것이며, 그 자체로는 목표가 아닙니다. 당신은 정말로 기억하기 쉽거나 타이핑하기 쉽다는 것을 의미합니다.

기억하기 쉽다는 의미라면 뒤로 물러서야합니다. 우리는 여전히 같은 크기이며 다르게 인코딩되었습니다. 그러나 사용자는 글자가 ‘A-F’로 제한되어 있다는 것을 알지 못하므로 문자 ‘AZ’가 허용되는 것처럼 ID는 동일한 개념 공간을 차지합니다. 따라서 전화 번호를 외우는 대신 GUID를 같은 길이로 외우는 것과 같습니다.

입력하려는 경우 키패드를 사용하는 대신 키보드의 주요 부분을 사용해야합니다. 손가락이 인식하는 단어가 아니기 때문에 입력하기가 더 어려울 수 있습니다.

더 나은 옵션은 실제로 실제 사용자 이름을 선택하도록하는 것입니다.


답변

16 진수로 :

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

int로 :

int intValue = int.Parse(hex, System.Globalization.NumberStyles.HexNumber)


답변

이 답변을 찾기 전에 int를 16 진수 문자열로 변환하고 다시 변환하는 자체 솔루션을 만들었습니다. 당연히 코드 오버 헤드가 적기 때문에 .net 솔루션보다 훨씬 빠릅니다.

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

타이밍 코드 :

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

결과 :

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