Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big number in C#.NET

Tags:

c#

php

I have to create a method that verify if a number follow a certain structure, and it must follow a existing pattern implemented in PHP, but I'm having certain trouble doing thins in C#.NET. When the number went too long I got a System.OverflowException, I'm using ulong, take a look:

    /// <summary>
    /// Gera um dígito verificador para um código
    /// </summary>
    /// <param name="code">Código</param>
    /// <returns>Digito verificador</returns>
    public static ulong GenerateTrustID(UInt64 code)
    {
        UInt64 intcode = 1;
        UInt64 endcode = 0;

        foreach (UInt64 number in code.ToString().ToCharArray().Select(Convert.ToInt64).ToArray())
        {
            UInt64 newcode = (number * code * intcode);

            char[] chrcode = newcode.ToString().ToCharArray();
            Array.Reverse(chrcode);
            intcode = UInt64.Parse((new string(chrcode)));
        }

        if (intcode.ToString().Length < 2)
        { 
            intcode = 04051995;
            intcode = intcode * 88;
        }

        endcode = UInt64.Parse(intcode.ToString().GetLast(2));

        return endcode;
    }

And I have to reproduce the code below:

/**
 * @brief   Gera uma ID de verificação para um código em um esquema privado.
 * @param   int $code Código para o qual será gerado o ID de verificação
 * @return  int
 */
public function generateTrustID($code){
    $intcode = 1;
    $endcode = null;
    $numbers = array_map('intval', str_split($code));

    foreach($numbers as $number){
        $intcode = (int)strrev($number * $code * $intcode);
    }

    if(strlen($intcode) < 2){
        $intcode = 04051995;
        $intcode = $intcode * 88;
    }

    $endcode = substr($intcode, 0, 2);

    return $endcode;
}
like image 847
hamboldt Avatar asked Sep 27 '22 15:09

hamboldt


1 Answers

For really large numbers you can use the BigInteger Class.

You can also read this article for more information on how to use it.

like image 97
Fahad Jameel Avatar answered Oct 05 '22 06:10

Fahad Jameel