English 中文(简体)
避免在C++中将未签字的流入转换为固定的仓储,有什么有效的方法?
原标题:What s an efficient way to avoid integer overflow converting an unsigned int to int in C++?

Is the following an efficient and problem free way to convert an unsigned int to an int in C++:

#include <limits.h>
void safeConvert(unsigned int passed) 
{
    int variable = static_cast<int>(passed % (INT_MAX+1)); 
    ...
}

还是有更好的办法?

UPDATE

www.un.org/Depts/DGACM/index_spanish.htm 正如James McNellis所指出的,没有定义指定一个未签字的“t >”号;INT_max为一种分类,而是界定了这一执行。 因此,我现在特别想到的是,在未签名的电文超过INT_/2008/5时,确保这种电汇折价为零。

我有一些未经签名的暗中 s作为反.,但希望在某个具体案件中将其环绕成ger。

按照正常操作,这些计数将保持在INT_max的范围之内。 然而,如果出现异常(但有效)的情况,为了避免进入un Defin执行特定行为,我想在此作一些有效的转换。

最佳回答

This should also work:

int variable = passed & INT_MAX;
问题回答

按照正常操作,这些计数将保持在INT_max的范围之内。 然而,如果出现异常(但有效)案件,为了避免陷入不明确的行为,我在此想作一些有效的转变。

有效转换到什么? 如果所有未签字的现存价值都相应,而且你想要其他未签字的数值,例如INT_/2008/5+1,则每个数值都有不同的数值,那么你只能将其描绘成负的分类值。 这样做是默认的,可以明确要求使用<编码>static_cast<int>my_unsign)。 否则,你可以将其全部图画到0或1,或INT_MIN,或抛开高轨道......最容易的是:if (my_unsign > INT_/2008/5) my_unsign = XXX,或.my_unsign &=INT_/2008/5/code>以清除高轨道。 但是,如果<代码>int超支,所叫的职能将适当运作吗? 也许更好的解决办法是首先利用64个轨道点?





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签