In C# can casting a Char to Int32 produce a negative value?

。_饼干妹妹 提交于 2019-12-19 19:52:00

问题


Or is it always guaranteed to be positive for all possible Chars?


回答1:


It's guaranteed to be non-negative.

char is an unsigned 16-bit value.

From section 4.1.5 of the C# 4 spec:

The char type represents unsigned 16-bit integers with values between 0 and 65535. The set of possible values for the char type corresponds to the Unicode character set. Although char has the same representation as ushort, not all operations permitted on one type are permitted on the other.




回答2:


Since the range of char is U+0000 to U+ffff, then a cast to an Int32 will always be positive.




回答3:


Each 16-bit value ranges from hexadecimal 0x0000 through 0xFFFF and is stored in a Char structure.

Char Structure - MSDN




回答4:


See Microsoft's documentation

There you can see, that Char is a 16 bit value in the range of U+0000 to U+ffff. If you cast it to a Int32, there should be no negative value.




回答5:


char can be inplicitly converted to ushort and ushort range is 0 to 65,535 so its always positive



来源:https://stackoverflow.com/questions/7820365/in-c-sharp-can-casting-a-char-to-int32-produce-a-negative-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!