gpt4 book ai didi

c++ - 检测整数截断

转载 作者:行者123 更新时间:2023-11-30 01:29:35 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Best way to detect integer overflow in C/C++

检测是否发生整数截断的最佳方法是什么?
编辑
这应该会导致发出截断信号,但它不会

#include <iostream>

using std::cout;
typedef signed int int32_t;
typedef unsigned int uint32_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;


int32_t my32bitInt = 0xffffffff;

int32_t tmp = my32bitInt & 0xFFFF8000;

uint16_t ss = my32bitInt;

int main()
{

if (tmp != 0xFFFF8000 && tmp != 0x00000000)
{ // cannot be converted safely
cout << "truncation";
}
cout << ss << '\n';
cout << my32bitInt << '\n';
return 0;
}

编辑2

template <typename U, typename T>
bool is_safe(T t)
{
return sizeof(U) <= sizeof(T) ?
(t >= static_cast<T>(std::numeric_limits<U>::min()))
&& (t <= static_cast<T>(std::numeric_limits<U>::max())) : true;
}

编辑 3(基于 Oli 的 <>)- 我发现了一些问题,但正在努力,会尽快更新

模板bool is_safe(源值){

if (sizeof(Result) == sizeof(Source))
{/*Same size*/

if (std::is_same<Source,Result>::value)
{
//signed to signed or unsigned to unsigned when size is same - no problem
return true;
}
else
{
//MSB mustn't be set in Source
return !(value & (1u << ((sizeof(Source) * CHAR_BIT) - 1)));
}
}
else
{//smaller to larger and larger to smaller

if (sizeof(Result) <= sizeof(Source))
{ //Larger to smaller and both equal
return ((value >= static_cast<Source>(std::numeric_limits<Result>::min()))
&& (value <= static_cast<Source>(std::numeric_limits<Result>::max())));
}
else
{ //smaller to larger

if (std::is_signed<Source>::value && !std::is_signed<Result>::value)
{
//signed to unsigned - signed must be positive
return (value >= 0);
}
else
{
return true;
}
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com