In 这个答案 https://stackoverflow.com/a/51234964/65863, 你可以找到这条评论 https://stackoverflow.com/questions/40608111/why-is-18446744073709551615-1-true/51234964#comment89450401_51234964:
严格来说,转换前两个数字的位表示相同并不重要。即使使用 1 的补码或带符号的幅度表示,(signed) -1 到 unsigned long 的转换总是会导致ULONG_MAX
.(当然,转换后的位模式将是相同的)。
我明白你可以代表-1
以除补码之外的其他方式,这是我的答案中应该包含的有效补充。但是,在这样的实现中,依赖于转换是否安全?ULONG_MAX
?
是的,无论实际表示如何,这都是保证的:
[转化积分] https://timsong-cpp.github.io/cppwp/n4659/conv.integral(强调我的)
整数类型的纯右值可以转换为另一个整数类型的纯右值
整数类型。无作用域枚举类型的纯右值可以是
转换为整数类型的纯右值。
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n
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 ]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)