Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to bit-copy a signed integer to an unsigned integer

Tags:

c++

c

/* [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?


1 Answers

/* [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);
like image 110
Drax Avatar answered Sep 13 '25 15:09

Drax