为什么在C#中执行按位运算时必须强制转换为0(零)? [英] Why do I have to cast 0 (zero) when doing bitwise operations in C#?

查看:101
本文介绍了为什么在C#中执行按位运算时必须强制转换为0(零)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码对我解压缩的12位值从1.5字节扩展为16位:

I am using the following code to sign extend a 12 bit value I unpacked from 1.5 bytes to 16 bits:

word[0] |= ((word[0] & 0x800) != 0 ? (Int16)(-4096) : (Int16)0);

如果我不将最后一个零强制转换为Int16,则会收到编译器的以下投诉:

If I don't cast the last zero to Int16 I get the following complaints from the compiler:

Warning 1   Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first
Error   2   Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

这是为什么?我知道C#在执行按位运算时会将所有内容转换为int,但是通常整数常量会自动获得正确的类型.例如,如果将零赋给浮点数,则不必强制将其强制转换为浮点数.我是C程序员,所以在回答:-)

Why is this? I understand that C# converts everything to an int when doing bitwise operations, but normally integer constants are automatically given the right type. If I assign zero to a float I don't have to cast it to float first, for example. I'm a C programmer, so please keep that in mind when answering :-)

推荐答案

C#中唯一的整数文字类型用于 int uint ulong ( C#语言规范,版本5 ,第2.4.4.2节).任何文字(例如 0 )都只能将其类型推断为这4个字符之一(并且没有任何额外的指示,它是 int ).

The only types of integer literals in C# are for the types int, uint, long, and ulong (C# Language specification, version 5, section 2.4.4.2). Any literal (such as 0) will only have its type inferred as one of those 4 (and without any extra indications, it's an int).

那么,为什么呢?

short s = 0;

工作吗?那是由于隐式常量表达式转换(第6.1.9节):

work? That would be due to Implicit constant expression conversions (section 6.1.9):

类型为 int constant-expression (第7.19节)可以转换为类型 sbyte byte short ushort uint ulong ,只要提供 constant-expression 在目标类型的范围内.

A constant-expression (§7.19) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.

但是,我们在这里使用的不是常量表达式.因此,所有常规的C#输入规则都可以发挥作用.在分析条件运算符时(第7.14节),类型为:

But, what we're working with here isn't a constant expression. So all of the conventional C# typing rules come into play; When analyzing the conditional operator (section 7.14), the types are:

bool ? short : int;

然后编译器(不能使用上面的 constant-expression 规则)确定该表达式的类型为 int ,因为 short 可以隐式转换为 int ,反之亦然.

And the compiler (without being able to use the above constant-expression rule) decides that the type of that expression is int, since a short may be implicitly converted to an int, but not vice-versa.

这篇关于为什么在C#中执行按位运算时必须强制转换为0(零)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆