August Flanagan
August Flanagan

Reputation: 896

Integer concatenation c

I'm trying to concatenate two uint32_t and get back a uint64_t. Here's my method

uint64_t concat_int1_int2 (uint32_t int1, uint32_t int2) {
  uint64_t concatenated = int1;
  return concatenated << 32 | int2;
}

This seems to be extremely slow (I need to do it ~1,000,000 times and it is taking ~ 6 minutes). Two questions, why does the bit shift take so long (that seems to be the limiting step), and does anyone have a suggestion for a faster way to do this?

Upvotes: 7

Views: 800

Answers (3)

lvella
lvella

Reputation: 13491

Your solution is near optiomal, it can't be much faster. Marking the function as inline may help a very little, but will not make much difference. I made a test here in my machine using your code, it took 10ms to run 1,000,000 iterations of it. Your speed problem is somewhere else.

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182883

The way you are doing it is correct. It may help to inline the function. Most likely your performance problem is in code you haven't shown us.

Upvotes: 5

Joel Spolsky
Joel Spolsky

Reputation: 33697

Why bitshift? Just shovel the 32 bit ints into the appropriate memory locations. Something like:

 *((uint32_t*) concatenated) = int1;
 *(((uint32_t*) concatenated)+1) = int2;

Now that I've given you that idea, note that in this function, int1 and int2 are ALREADY next to each other on the stack. So if they're in the right order, merely casting one of the parameters to a uint64_t does what you want! Yay pointers!

Upvotes: -1

Related Questions