解释签名为unsigned [英] interpret signed as unsigned

查看:137
本文介绍了解释签名为unsigned的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的值:

int64_t s_val = SOME_SIGNED_VALUE;

如何获得

uint64_t u_val

$ c> s_val ,但是被视为无符号?

that has exactly the same bit pattern as s_val, but is treated as unsigned?

这可能很简单,但是在Stackoverflow和其他地方

This may be really simple, but after looking on Stackoverflow and elsewhere I haven't turned up the answer.

推荐答案

int64_t s_val = SOME_SIGNED_VALUE;
uint64_t u_val = static_cast<uint64_t>(s_val);

C ++ Standard 4.7 / 2声明:

C++ Standard 4.7/2 states that:

如果目标类型是无符号的,则结果值是与源整数一致的最小无符号整数(模2 n ,其中n是用于表示无符号类型)。 [注意:在二进制补码表示中,此转换是概念性的,并且位模式没有变化(如果没有截断)。 ]

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). ]

另一方面,Standard说由 reinterpret_cast 是实现定义的。[注:它可能或可能不会产生与原始值不同的表示。](5.2.10 / 3)。所以,我建议使用 static_cast

From the other hand, Standard says that "The mapping performed by reinterpret_cast is implementation-defined. [Note: it might, or might not, produce a representation different from the original value. ]" (5.2.10/3). So, I'd recommend to use static_cast.

这篇关于解释签名为unsigned的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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