Come posso convertire un grande numero decimale in esadecimale in C # (ad esempio: 588063595292424954445828)

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

Domanda

Il numero è maggiore di int & amp; long ma può essere inserito in Decimal . Ma i normali metodi ToString o Convert non funzionano su Decimal .

È stato utile?

Soluzione

Credo che questo produrrà i risultati giusti dove restituisce qualcosa, ma può rifiutare numeri interi validi. Oserei dire che può essere risolto con un po 'di sforzo però ... (Oh, e al momento fallirà anche per i numeri negativi.)

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

Altri suggerimenti

Devo essere d'accordo con James - fallo manualmente - ma non usare base-16. Usa la base 2 ^ 32 e stampa 8 cifre esadecimali alla volta.

Immagino che un'opzione sarebbe quella di continuare a toglierle e convertirle? Un po 'di mod / divisione ecc., Convertendo singoli frammenti ...

Quindi: quale valore esadecimale ti aspetti?

Ecco due approcci ... uno usa la struttura binaria del decimale; uno lo fa manualmente. In realtà, potresti voler fare un test: se i bit [3] sono zero, fallo nel modo più veloce, altrimenti fallo manualmente.

    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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top