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

后端 未结 5 844
时光取名叫无心
时光取名叫无心 2021-01-18 11:03

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

相关标签:
5条回答
  • 2021-01-18 11:36

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

    Char Structure - MSDN

    0 讨论(0)
  • 2021-01-18 11:42

    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.

    0 讨论(0)
  • 2021-01-18 11:49

    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.

    0 讨论(0)
  • 2021-01-18 11:51

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

    0 讨论(0)
  • 2021-01-18 11:51

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

    0 讨论(0)
提交回复
热议问题