C# (예 : 58806359524249544445828)에서 큰 십진수를 16 진수로 변환하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/221154

문제

숫자는보다 큽니다 int & long 그러나 수용 할 수 있습니다 Decimal. 그러나 정상 ToString 또는 Convert 방법은 작동하지 않습니다 Decimal.

도움이 되었습니까?

해결책

나는 이것이 무엇이든 반환하는 올바른 결과를 얻을 수 있지만 유효한 정수를 거부 할 수 있다고 생각합니다. 나는 약간의 노력으로 일할 수 있다고 감히 ... (아, 그리고 그것은 또한 순간에도 마이너스 횟수에 실패 할 것입니다.)

static string ConvertToHex(decimal d)
{
    int[] bits = decimal.GetBits(d);
    if (bits[3] != 0) // Sign and exponent
    {
        throw new ArgumentException();
    }
    return string.Format("{0:x8}{1:x8}{2:x8}",
        (uint)bits[2], (uint)bits[1], (uint)bits[0]);
}

다른 팁

제임스와 동의해야합니다 - 수동으로하십시오 - 그러나 Base -16을 사용하지 마십시오. 베이스 2^32를 사용하고 한 번에 8 개의 16 진수를 인쇄하십시오.

한 가지 옵션이 덩어리를 계속 벗고 개별 청크를 변환하는 것 같아요? 약간의 모드/분할 등, 개별 조각을 변환 ...

그래서 : 어떤 16 진수 가치를 기대하십니까?

두 가지 접근법이 있습니다 ... 하나는 소수점의 이진 구조를 사용합니다. 하나는 수동으로 수행합니다. 실제로 테스트를 원할 수도 있습니다. 만약에 비트 [3]은 0입니다. 그렇지 않으면 수동으로 수행하십시오.

    decimal d = 588063595292424954445828M;
    int[] bits = decimal.GetBits(d);
    if (bits[3] != 0) throw new InvalidOperationException("Only +ve integers supported!");
    string s = Convert.ToString(bits[2], 16).PadLeft(8,'0') // high
            + Convert.ToString(bits[1], 16).PadLeft(8, '0') // middle
            + Convert.ToString(bits[0], 16).PadLeft(8, '0'); // low
    Console.WriteLine(s);

    /* or Jon's much tidier: string.Format("{0:x8}{1:x8}{2:x8}",
            (uint)bits[2], (uint)bits[1], (uint)bits[0]);  */

    const decimal chunk = (decimal)(1 << 16);
    StringBuilder sb = new StringBuilder();
    while (d > 0)
    {
        int fragment = (int) (d % chunk);
        sb.Insert(0, Convert.ToString(fragment, 16).PadLeft(4, '0'));
        d -= fragment;
        d /= chunk;
    }
    Console.WriteLine(sb);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top