Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is BigInteger in C# a struct if it has an unbounded size?

Tags:

c#

.net

struct

Why is BigInteger declared as a ValueType (struct) in C#? It seems to be very similar to the string type which is declared as a reference type.

Both are immutable (value types). Both can be arbitrarily large.

The recommendation I have heard is that a struct should never be more than 16 Bytes. BigInteger can get much larger than 16 Bytes and I would think this would make frequent operations extremely slow since it is always copied by value.

like image 766
Jacob Schneider Avatar asked Dec 03 '15 17:12

Jacob Schneider


People also ask

What is BigInteger in C?

The BIGINT data type is a machine-independent method for representing numbers in the range of -2 63-1 to 2 63-1. ESQL/C provides routines that facilitate the conversion from the BIGINT data type to other data types in the C language. The BIGINT data type is internally represented with the ifx_int8_t structure.

Why do we use BigInt?

BigInt is a new data type intended for use when integer values are larger than the range supported by the Number data type. This data type allows us to safely perform arithmetic operations on large integers, represent high-resolution timestamps, use large integer IDs, and more without the need to use a library.

What is the difference between integer and BigInteger?

Remarks. The int data type is the primary integer data type in SQL Server. The bigint data type is intended for use when integer values might exceed the range that is supported by the int data type. bigint fits between smallmoney and int in the data type precedence chart.

Does C++ have a BigInteger class?

This is a Big Integer Class, implemented in C++, for handling very large numbers, or numbers greater than unsigned long long int in a 64 bit implementation. So, it can easily operate on numbers greater than 10^18.


1 Answers

Copying a BigInteger does not cause the underlying data to be copied. Instead, just a reference to the data is copied.

Since BigInteger values are immutable it is safe for two or more values to share a common data buffer.

BigInteger has two instance fields:

  • int _sign - probably tells whether its a positive or negative value.
  • uint[] _bits - this is a reference to the data buffer.

An int is 4 bytes and a reference is 8 bytes (on a 64-bit system). Therefore the size of a BigInteger is ≤ 16 bytes.

like image 182
Mårten Wikström Avatar answered Sep 30 '22 06:09

Mårten Wikström