64位Int的移位错误

时间:2016-02-07 22:06:17

标签: c# bit-manipulation

我正在尝试使用UInt64数据类型进行位移。当我使用常数时,代码就像我预期的那样工作。但是,当我使用变量时,它会失败。编译器发出"运算符<<不能应用于' int'类型的操作数和' ulong'"错误。如何修复此代码以便我可以使用变量代替常数?这是我的代码的摘录

using System.IO;
using System;

class Program
{
    static void Main()
    {
       UInt64 x=0;
       int pos = 2;
       x = ((UInt64)x | (1 << pos));
       Console.WriteLine(x);
    }
}

1 个答案:

答案 0 :(得分:2)

尝试制作UInt64的右侧操作数 - 运算符的类型为x = x | (1UL << pos); ,例如:

x |= 1UL << pos;
BTW,人们可能更喜欢化合物形式:

numberOfRowsInSection: