Reputation: 33
I've got an unsigned
and would like to convert that to an uint64_t
(and back if possible).
How do I do that? If possible, I would like to avoid depending on undefined behaviour.
Thanks!
Upvotes: 3
Views: 13555
Reputation: 400129
For instance:
const uint64_t bigvalue = (uint64_t) 42u;
Not sure if the cast is even necessary, since this doesn't loose information. The opposite:
const unsigned int smallvalue = (unsigned int) bigvalue;
will need the cast, since it's (probably, assuming int
< uint64_t
) a more narrow type.
Note: I mean "need" in a weak sense; since there is a risk of losing information when converting to a more narrow type, it's likely that compilers will warn. The cast adds a sense of "I know what I'm doing" which is how such warnings are typically silenced.
Upvotes: 3
Reputation: 11900
You can do it with typecasting:
uint64_t new = (uint64_t) old;
Where old
is your unsigned int.
Upvotes: 0
Reputation: 183978
The conversion to unsigned integer types from any integer types is completely defined by the standard (section 6.3.1.3, paragraph 2). If the value can be represented in the target type, it is preserved, otherwise the value is reduced modulo 2^WIDTH
, where WIDTH
is the width (number of value bits) of the target type.
Upvotes: 6
Reputation: 9642
Since you're in C land, a cast will be your only way. Simply do
uint64_t foo = (uint64_t)myVar;
Or, in reverse
unsigned int bar = (unsigned int)foo;
Your compiler should pick up the conversion automatically though, although in the case of a uint64_t
-> unsigned int
, you should get a warning regarding truncation. Also, the value will of course be truncated when converting back, unless you are compiling in a 64-bit environment.
Upvotes: -1