简体   繁体   English

在有符号和无符号之间进行转换

[英]Casting between signed and unsigned

Is this safe: 这安全吗?

int main()
{
    boost::int16_t t1 = 50000; // overflow here.
    boost::uint16_t t2 = (boost::uint16_t)t1;
    std::cout << t1 << " "  << t2 <<  std::endl;
}

To be even more specific: I'm storing this data in a table which is using signed types in its schema, is it safe to store, and retrieve this data in this manner? 更具体而言:我将这些数据存储在一个表中,该表在其架构中使用带符号的类型,这样是否可以安全地存储和检索该数据?

Thanks! 谢谢!

No, I believe this is implementation defined. 不,我相信这是实现定义的。 From the C++ draft standard, §4.7/3 根据C ++草案标准§4.7/ 3

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. 否则,该值由实现定义。

This applies to the first statement. 这适用于第一条陈述。 int16_t is signed, and it can not represent 50000. So the value of t1 depends on the implementation. int16_t是带符号的,不能表示50000。因此t1的值取决于实现。

Once you know t1 , t2 is guaranteed by §4.7/2 to be the lowest uint16_t congruent modulus 2^16 to t1 . 一旦你知道了t1t2由§4.7/ 2是最低保证uint16_t全等模2 ^ 16至t1 Basically, t1 mod 2^16. 基本上是t1 mod 2 ^ 16。

I'd say it's safe, but why not using an uint16_t without going through this misleading cast? 我会说这是安全的,但是为什么不使用uint16_t而不经历这种误导性的转换呢?

Types exists for communication also, not only for the sake of compilation process. 类型也存在用于通信,不仅是为了编译过程。

Assigning a number that cannot be represented in a signed type is implementation-defined. 分配不能以签名类型表示的数字是实现定义的。 The next conversion however has a standard defined behaviour. 但是,下一次转换具有标准定义的行为。 So the outcome of the function is implementation defined, if that is safe or not, is a subjective matter. 因此,函数的结果是实现定义的定义,无论是否安全,都是主观的。 But portable across platforms or compilers it is not. 但是它不能跨平台或编译器移植。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM