2012-04-24 20 views
7

¿Cómo puedo implementar este código python en C#?enteros arbitrariamente grandes en C#

código Python:

print(str(int(str("e60f553e42aa44aebf1d6723b0be7541"), 16))) 

Resultado:

305802052421002911840647389720929531201 

pero en C# tengo problemas con dígitos grandes.

¿Me puede ayudar?

Tengo resultados diferentes en python y C#. Donde puede ser un error?

Respuesta

18

Los tipos primitivos (como Int32, Int64) tienen una longitud finita que no es suficiente para un número tan grande. Por ejemplo:

 
Data type          Maximum positive value 
Int32             2,147,483,647 
UInt32             4,294,967,295 
Int64          9,223,372,036,854,775,808 
UInt64         18,446,744,073,709,551,615 
Your number  305,802,052,421,002,911,840,647,389,720,929,531,201 

En este caso para representar ese número se necesitaría 128 bits. Con .NET Framework 4.0 hay un nuevo tipo de datos para números enteros de tamaño arbitrario System.Numerics.BigInteger. No necesita especificar ningún tamaño porque será inferido por el número mismo (significa que incluso puede obtener un OutOfMemoryException cuando realiza, por ejemplo, una multiplicación de dos números muy grandes).

volver a su pregunta, en primer lugar analizar el número hexadecimal:

string bigNumberAsText = "e60f553e42aa44aebf1d6723b0be7541"; 
BigInteger bigNumber = BigInteger.Parse(bigNumberAsText, 
    NumberStyles.AllowHexSpecifier); 

Después, simplemente imprimirlo a la consola:

Console.WriteLine(bigNumber.ToString()); 

te puede ser interesante para calcular la cantidad de bits que necesita para representar un número arbitrario, utilice esta función (si recuerdo bien, la implementación original proviene de C Numerical Recipes):

public static uint GetNeededBitsToRepresentInteger(BigInteger value) 
{ 
    uint neededBits = 0; 
    while (value != 0) 
    { 
     value >>= 1; 
     ++neededBits; 
    } 

    return neededBits; 
} 

entonces para calcular el tamaño requerido de un número como cadena escribió:

public static uint GetNeededBitsToRepresentInteger(string value, 
    NumberStyles numberStyle = NumberStyles.None) 
{ 
    return GetNeededBitsToRepresentInteger(
     BigInteger.Parse(value, numberStyle)); 
} 
+0

Gracias! ¡Funciona! Pero devuelve un resultado incorrecto, es cuestión de tiempo. quizás ... =) – pic0

Cuestiones relacionadas