How to concatenate two integers in C

010110110101 picture 010110110101 · Oct 3, 2012 · Viewed 75.9k times · Source

Stack Overflow has this question answered in many other languages, but not C. So I thought I'd ask, since I have the same issue.

How does one concatenate two integers in C?

Example:

x = 11;
y = 11;

I would like z as follows:

z = 1111;

Other examples attempt to do this with strings. What is a way to do this without strings?

I'm looking for an efficient way to do this in C because in my particular usage, this is going into a time critical part of code.

Thanks in Advance!

Answer

Mooing Duck picture Mooing Duck · Oct 3, 2012
unsigned concatenate(unsigned x, unsigned y) {
    unsigned pow = 10;
    while(y >= pow)
        pow *= 10;
    return x * pow + y;        
}

Proof of compilation/correctness/speed

I avoid the log10 and pow functions, because I'm pretty sure they use floating point and are slowish, so this might be faster on your machine. Maybe. Profile.