What is an efficient way to avoid integer overflow converting unsigned int to int in C ++?

It is the following efficient and hassle-free way to convert an unsigned int to int in C ++:

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

Or is there a better way?

UPDATE

As James McNellis noted, it is not undefined to assign unsigned int> INT_MAX to an integer - rather, this implementation is defined. So the context here currently definitely depends on my preference, to ensure that this integer is reset to zero when the unsigned int exceeds INT_MAX.

Source context

I have an unsigned int number used as counters, but you want to pass them as integers in a specific case.

INT_MAX. , undefined, ( ) .

+3
2

:

int variable = passed & INT_MAX;
+7

INT_MAX. , undefined, ( ) , .

? int unsigned int , , , INT_MAX + 1, , . static_cast<int>(my_unsigned). 0 -1 INT_MIN ... : if (my_unsigned > INT_MAX) my_unsigned = XXX ...my_unsigned &= INT_MAX, . , int? , 64- int ?

0

Source: https://habr.com/ru/post/1795653/


All Articles