Applying bitwise or operator to decimal in c#
bit-manipulation, c#, decimal
Solution
Big numbers
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;
Really big numbers
Using .Net 4.0 or above
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.
Using .Net 2.0 or above
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#
Problem
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