In this code, I have a requirement like below:
decimal col;
if (condition)
{
(decimal)col = (decimal)col | ((decimal)System.Math.Pow(2, 0));
}
When this code is compiled, I get an error saying
Operator | cannot be applied to operands of type 'decimal' and 'decimal'
Can anyone explain, please? Thanks
As the compile-time-error says, you cannot use |
on decimal
. The decimal
type is for numbers like 12.34
. If you're only using numbers like 12
or 34
then you may be better off using int
(between ±2 billion) or long
(between ±9 quintillion) depending how big your integer is.
Any number raised to the power zero, n0 equals 1
so your Math.Pow(2, 0)
can be replaced by 1
.
Your code could then look like this, which will compile.
int col;
and
if (condition)
col = col | 1;
Finally, you may prefer to use the ternary operator ?:
to in-line your if
statement, do whichever is more readable in your situation:
col = condition ? (col | 1) : col;
If you need to use REALLY BIG integers, there is a class for that! System.Numerics.BigInteger
(in System.Numerics.dll
).
The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.
Your declaration would then become:
BigInteger col;
And your bitwise operations as normal.
Check out the project IntX
IntX is an arbitrary precision integers library written in pure C# 2.0 with fast - about O(N * log N) - multiplication/division algorithms implementation. It provides all the basic arithmetic operations on integers, comparing, bitwise shifting etc.
Reference: Big integers in C#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With