2012-03-29 32 views
3

我试图编译这段代码:位运算

Int64 itag = BitConverter.ToInt64(temp, 0); 
itag &= 0xFFFFFFFFFFFFFC00; 

但是这给了我以下错误:

Operator '&=' cannot be applied to operands of type 'long' and 'ulong'

我该怎么办呢?

+4

你有没有尝试过宣称你的itag是ulong? – 2012-03-29 11:53:05

+0

@RoyDictus,这实际上解决了问题!我想知道为什么?该错误明确指出'&='不适用于'long'或'ulong'。这怎么可能? – atoMerz 2012-03-29 11:57:13

+1

VS2010编译并运行这两行而不会发痒。什么是'somval'? – Alex 2012-03-29 11:57:24

回答

4

http://msdn.microsoft.com/en-en/library/aa664674%28v=vs.71%29.aspx

If the literal has no suffix, it has the first of these types in which its value can be represented: int , uint , long , ulong .

你有

0xFFFFFFFFFFFFFC00 

但Int64.Max是:

0x7FFFFFFFFFFFFFFF 

所以long不够大,ulong被当作文字的类型。

现在你对左侧Int64,这是签署,并在右边你有ulong,但是,没有的&=超载它接受组合,这导致了错误。

+0

感谢您的好解释。 – atoMerz 2012-03-29 12:16:51

1

签名和未签名的“数字”不能混合匹配,并且Int64已签名,因此它是不可用的。

我想是这样的:

UInt64 itag = BitConverter.ToUInt64(temp, 0); //note the added 'U' to make it unsigned 
itag &= 0xFFFFFFFFFFFFFC00; //Now types match, they're both unsigned. 
+0

有一件事我不明白,为什么'0xFFFFFFFFFFFFFC00'被视为无符号?在C#中是否是十六进制字面值无符号? – atoMerz 2012-03-29 12:08:11

+0

@AtoMerZ:查看我的答案。 – 2012-03-29 12:10:14

+0

正如Marcus Meitzler在他的回答中及时指出的那样,对于签名类型,值太大 – Alex 2012-03-29 12:12:33

2

C#使用整数文字的最小拟合类型,而0xFFFFFFFFFFFFFC00太长而不能长,所以它是一个ulong。

因此要么将itag转换为ulong或0xFFFFFFFFFFFFFC00长(未选中)。

+1

这应该是一个评论,但它是正确的。 – Alex 2012-03-29 12:13:14

1

itag是一个长。 0xFFFFFFFFFFFFFC00是一个ulong。您正尝试在&=声明中混合使用,但这种声明不起作用。

为什么你的字面值过大? MSDN says

If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

自号是INT,UINT或长太大,你的文字成为一个ULONG。

你有两个选择:要么宣布itag作为ULONG,正如其他人的建议,或(位)转换您的文字为长:

itag &= unchecked((long)0xFFFFFFFFFFFFFC00); 

这会溢出你ULONG成(负)长。

+0

引用 - >如果文字没有后缀,它具有第一个可以表示其值的类型:int,uint,** long **,ulong。这么长时间是一个选择。 – atoMerz 2012-03-29 12:14:44

+1

'长'最大值是'0x7FFFFFFFFFFFFFFF',所以你的文字不适合'长'。 – 2012-03-29 12:17:48

0

的问题是,你要&=一个longulong

只需将Int64替换为ulong即可解决问题,因为您正在将&=应用于2 ulong s。

1

第7.11节。1个整数逻辑运算符的C#语言规范的读取:

The predefined integer logical operators are:

int operator &(int x, int y);

uint operator &(uint x, uint y);

long operator &(long x, long y);

ulong operator &(ulong x, ulong y);

正如你可以看到,有long之间没有预定义的运算符(这仅仅是一个Int64别名)和ulong,因此错误。