Net*_*hie 2 c# bit-manipulation decimal
在此代码中,我有如下要求:
decimal col;
if (condition)
{
(decimal)col = (decimal)col | ((decimal)System.Math.Pow(2, 0));
}
Run Code Online (Sandbox Code Playgroud)
编译此代码时,我收到错误消息
Operator | cannot be applied to operands of type 'decimal' and 'decimal'
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下吗?谢谢
正如编译时错误所说,你不能使用|on decimal.该decimal类型是相同的数字12.34.如果你只是使用类似的数字12,34那么你可能最好使用int(在±20亿long之间)或(在±9之间)取决于你的整数有多大.
任何数字上升到幂0,n 0等于1所以你Math.Pow(2, 0)可以被替换为1.
您的代码可能看起来像这样,将编译.
int col;
Run Code Online (Sandbox Code Playgroud)
和
if (condition)
col = col | 1;
Run Code Online (Sandbox Code Playgroud)
最后,您可能更愿意使用三元运算符?:来嵌入您的if语句,在您的情况下执行更具可读性的操作:
col = condition ? (col | 1) : col;
Run Code Online (Sandbox Code Playgroud)
如果你需要使用REALLY BIG整数,那就有一个类!System.Numerics.BigInteger(in System.Numerics.dll).
BigInteger类型是一个不可变类型,表示一个任意大的整数,其理论上的值没有上限或下限.
您的声明将成为:
BigInteger col;
Run Code Online (Sandbox Code Playgroud)
你的按位操作正常.
查看IntX项目
IntX是一个用纯C#2.0编写的任意精度整数库,具有快速 - 约O(N*log N) - 乘法/除法算法实现.它提供了对整数,比较,按位移位等所有基本算术运算.
参考:C#中的大整数