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 int
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 int
, especially when the unsigned long int
is larger than an int
?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With