Ross Ross - 1 year ago 58
C++ Question

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

I have an app which is creating unique ids in the form of

unsigned long int
s. The app needs this precision.

However, I have to send these ids in a protocol that only allows for
s. 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
, especially when the
unsigned long int
is larger than an


The protocol only supports
. 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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download