Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I safely convert `unsigned long int` to `int`?

Tags:

c++

I have an app which is creating unique ids in the form of unsigned long ints. The app needs this precision.

However, I have to send these ids in a protocol that only allows for ints. The receiving application – of the protocol – does not need this precision. So my questions is: how can I convert an unsigned long int to an int, especially when the unsigned long int is larger than an int?

edit:

The protocol only supports int. I would be good to know how to avoid "roll-over problems"

The application sending the message needs to know the uniqueness for a long period of time, whereas the receiver needs to know the uniqueness only over a short period of time.

like image 413
Ross Avatar asked Jul 08 '12 22:07

Ross


2 Answers

Here's one possible approach:

#include <climits>
unsigned long int uid = ...;
int abbreviated_uid = uid & INT_MAX;

If int is 32 bits, for example, this discards all but the low-order 31 bits of the UID. It will only yield non-negative values.

This loses information from the original uid, but you indicated that that's not a problem.

But your question is vague enough that it's hard to tell whether this will suit your purposes.

like image 98
Keith Thompson Avatar answered Nov 15 '22 22:11

Keith Thompson


Boost has numeric_cast:

unsigned long l = ...;
int i = boost::numeric_cast<int>(l);

This will throw an exception if the conversion would overflow, which may or may not be what you want.

like image 32
Philipp Avatar answered Nov 15 '22 23:11

Philipp