BigInteger を int に変換する

BigInteger を int へ変換するサンプルです。

// biginteger-to-int.cs
using System;
using System.Numerics;

class Program {
    static void Main() {
        var bigint = new BigInteger(1234567);
        int n = (int)bigint;
        Console.WriteLine(n);
    }
}

実行結果です。

$ mcs -r:System.Numerics biginteger-to-int.cs
$ mono biginteger-to-int.exe
1234567

int に収まらない場合は、System.OverflowException が生成されます。

// biginteger-to-int-overflow.cs
using System;
using System.Numerics;

class Program {
    static void Main() {
        var bigint = BigInteger.Parse("12345678901234567890");
        int n = (int)bigint; // int に収まらない
        Console.WriteLine(n);
    }
}

実行結果です。

$ mcs -r:System.Numerics biginteger-to-int-overflow.cs
$ mono biginteger-to-int-overflow.exe

Unhandled Exception:
System.OverflowException: Value was either too large or too small for an Int32.
   at System.Numerics.BigInteger.op_Explicit (BigInteger value) in <filename unknown>:line 0
   at Program.Main () in <filename unknown>:line 0
[ERROR] FATAL UNHANDLED EXCEPTION: System.OverflowException: Value was either too large or too small for an Int32.
   at System.Numerics.BigInteger.op_Explicit (BigInteger value) in <filename unknown>:line 0
   at Program.Main () in <filename unknown>:line 0

リンク