/* [1] */
int i = -1;
unsigned u = (unsigned)i;
/* [2] */
int i = -1;
unsigned u;
memcpy(&u, &i, sizeof i);
/* [3] */
int i = -1;
unsigned u = *(unsigned *)&i;
In order to bit-copy a signed integer to its unsigned partner, [1]
should work on most machines, but as far as I know it is not guaranteed behaviour.
[2]
should do exactly what I want, but I want to avoid the overhead of calling a library function.
So how about [3]
? Does it efficiently achieve what I intend?
/* [4] */
union unsigned_integer
{
int i;
unsigned u;
};
unsigned_integer ui;
ui.i = -1;
// You now have access to ui.u
Warning: As discussed in the comments, this seems to be okay in C
and Undefined Behaviour in C++
, since your question has both tags I'll leave this here. For more info check this SO question:
Accessing inactive union member and undefined behavior?
I would then advise for reinterpret_cast
in C++
:
/* [5] */
int i = -1;
unsigned u = reinterpret_cast<unsigned&>(i);
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