本文介绍了在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:

因此,在这个方向上,转换保留了位掩码.我不确定该标准是否保证从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:

这里的目的地类型"到底是什么意思?例如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的转换是否始终保留位模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:56