C#在内存中表示负整数的方式并将其转换为未选中状态 [英] The way C# represents negative integers in memory and casts them unchecked

查看:156
本文介绍了C#在内存中表示负整数的方式并将其转换为未选中状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#有各种各样的值类型,每种类型都有自己的用途。 Int32的范围从 - (0x7FFFFFFF + 1)到0x7FFFFFFF,并且从我运行它的每台机器,似乎unchecked((int)0xFFFFFFFF)总是得到一个结果值-1。总是这样吗?此外,在任何系统上,.NET总是在内存中表示-1为0xFFFFFFFF吗?领先位总是符号位吗?是否总是使用Two's Complement带符号的二进制表示形式?

C# has various value types, and each serves their own purpose. Int32 ranges from -(0x7FFFFFFF + 1) to 0x7FFFFFFF, and from every machine I've ever run it, it seems that unchecked((int)0xFFFFFFFF) always got me a resulting value of -1. Is this always the case? Furthermore, does .NET always represent -1 as 0xFFFFFFFF in memory on any system? Is the leading bit always the sign bit? Does it always use the Two's Complement signed binary representation for integers?

推荐答案

System.Int32 明确声明它存储在两个赞美形式中。它位于最底层:

The documentation for System.Int32 explicitly states that it is stored in two's compliment form. It's at the very bottom:


除了将单个整数作为十进制值使用之外,
可能还想执行按位运算使用整数值,或使用整数值的二进制或十六进制表示

Int32值以31位表示,第32位
用作符号位。使用
符号和幅度表示来表示正值。负值在两个
补码表示中。当
对Int32值执行按位运算或使用
单个位时,请务必记住这一点。为了对任何两个非十进制值执行数值,布尔或比较
操作,两个值必须使用相同的
表示。

In addition to working with individual integers as decimal values, you may want to perform bitwise operations with integer values, or work with the binary or hexadecimal representations of integer values. Int32 values are represented in 31 bits, with the thirty-second bit used as a sign bit. Positive values are represented by using sign-and-magnitude representation. Negative values are in two's complement representation. This is important to keep in mind when you perform bitwise operations on Int32 values or when you work with individual bits. In order to perform a numeric, Boolean, or comparison operation on any two non-decimal values, both values must use the same representation.

所以看来你所有问题的答案都是肯定的。

So it appears that the answer to all of your questions are yes.

Int32的范围也来自 - (0x80000000)到0x7FFFFFFFF。

Also the range for an Int32 is from -(0x80000000) to 0x7FFFFFFFF.

这篇关于C#在内存中表示负整数的方式并将其转换为未选中状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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