在C ++中,从unsigned int到int的转换是否始终保留位模式? [英] does in c++ the conversion from unsigned int to int always preserve the bit pattern?

查看:114
本文介绍了在C ++中,从unsigned int到int的转换是否始终保留位模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从标准(4.7)中看,当它们都使用相同数量的位时,从int到unsigned int的转换纯粹是概念性的:

From the standard (4.7) it looks like the conversion from int to unsigned int, when they both use the same number of bits, is purely conceptual:

如果目标类型是无符号的,则结果值是最小的 与源整数一致的无符号整数(取模2 n,其中n 是用于表示无符号类型的位数. [注意:在 用两个补码表示,这种转换是概念上的, 位模式没有变化(如果没有截断). - 结束语]

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2 n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]

因此,在这个方向上,转换保留了位掩码.我不确定该标准是否保证从unsigned int到int的转换相同(同样,假设使用相同的位数).这里的标准说:

So in this direction the conversion preserves the bitmask. I am not sure the standard guarantees the same for the conversion from unsigned int to int (again, assuming the same number of bits are used). The standard here says:

如果目标类型是带符号的,则该值可以保持不变 以目标类型(和位域宽度)表示;否则, 该值由实现定义.

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

这里的目的地类型"到底是什么意思?例如2 ^ 32-1不能用32位int表示.这是否意味着它不能以目标类型表示,因此不能假定位模式将保持不变?

What does it exactly mean "the destination type" here? For instance 2^32-1 cannot be represented by a 32 bit int. Does that mean that it cannot be represented in the destination type and therefore it cannot be assumed that the bit pattern will stay the same?

推荐答案

您不能假定任何内容.

第一个引号没有指出位掩码保持不变.补码可能相同,但补码或其他表示形式可能不同.

The first quote doesn't state that the bitmask remains the same. It may be the same in two's complement, but not in one's complement or other representations.

第二个定义为实现的意思是定义为实现,您通常不能假设任何事情.

Second, implementation-defined means implementation-defined, you can't assume anything in general.

理论上,每次转换后的表示形式可能完全不同.就是这样.

In theory, the representation can be completely different after each conversion. That's it.

如果您以现实的方式看待它,事情就会变得更加具体.通常,将int存储在二进制补码中,并且signed-> unsigned会像unsigned-> signed那样保留模式(由于可以实现定义该值,所以最便宜的方法是不执行任何操作).

If you look at it in a realistic way things come more concrete. Usually, int's are stored in two's complement and signed->unsigned preserves the pattern as unsigned->signed does (since the value can be implementation-defined, the cheapest way is doing nothing).

这篇关于在C ++中,从unsigned int到int的转换是否始终保留位模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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