如何在unsigned int和int之间安全地static_cast? [英] How does one safely static_cast between unsigned int and int?

查看:1364
本文介绍了如何在unsigned int和int之间安全地static_cast?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个8个字符 string 表示一个十六进制数,我需要将它转换为 int 。此转换必须保留字符串80000000和更高位的位模式,即这些数字应为负数。不幸的是,天真的解决方案:

I have an 8-character string representing a hexadecimal number and I need to convert it to an int. This conversion has to preserve the bit pattern for strings "80000000" and higher, i.e., those numbers should come out negative. Unfortunately, the naive solution:

int hex_str_to_int(const string hexStr)
{    
    stringstream strm;
    strm << hex << hexStr;
    unsigned int val = 0;
    strm >> val;
    return static_cast<int>(val);
}

不适用于我的编译器 val> ; MAX_INT (返回值为0)。将val的类型更改为 int 也会导致更大的数字为0。

doesn't work for my compiler if val > MAX_INT (the returned value is 0). Changing the type of val to int also results in a 0 for the larger numbers. I've tried several different solutions from various answers here on SO and haven't been successful yet.

以下是我所知道的:


  • 我在OpenVMS上使用HP的C ++编译器(使用,相信是安腾处理器)。


  • 从数字> INT_MAX到int的转换是由实现定义的。在我的机器上,它通常导致0,但有趣地从 int 结果

  • I'm using HP's C++ compiler on OpenVMS (using, I believe, an Itanium processor).
  • sizeof(int) will be at least 4 on every architecture my code will run on.
  • Casting from a number > INT_MAX to int is implementation-defined. On my machine, it usually results in a 0 but interestingly casting from long to int results in INT_MAX when the value is too big.

此值太大难以做到它已经为我。是否有人知道有便携式解决方案?

This is surprisingly difficult to do correctly, or at least it has been for me. Does anyone know of a portable solution to this?

更新:

static_cast 更改为 reinterpret_cast 会导致编译器错误。一个注释促使我尝试一个C风格的转型: return(int)val 在上面的代码,它的工作。

Changing static_cast to reinterpret_cast results in a compiler error. A comment prompted me to try a C-style cast: return (int)val in the code above, and it worked. On this machine. Will that still be safe on other architectures?

推荐答案

虽然有方法可以使用强制转换和转换,大多数依赖于未定义的行为,发生在一些机器/与一些编译器有明确定义的行为。而不是依赖未定义的行为,复制数据:

While there are ways to do this using casts and conversions, most rely on undefined behavior that happen to have well-defined behaviors on some machines / with some compilers. Instead of relying on undefined behavior, copy the data:

int signed_val;
std::memcpy (signed_val, val, sizeof(int));
return signed_val;

这篇关于如何在unsigned int和int之间安全地static_cast?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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