Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate two integers in C

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!

like image 286
101010 Avatar asked Oct 03 '12 00:10

101010


People also ask

How do you concatenate numbers?

This means that you can no longer perform any math operations on them. To combine numbers, use the CONCATENATE or CONCAT, TEXT or TEXTJOIN functions, and the ampersand (&) operator. Notes: In Excel 2016, Excel Mobile, and Excel for the web, CONCATENATE has been replaced with the CONCAT function.

Can we concatenate in C?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

What are concatenate digits?

The concatenation of two or more numbers is the number formed by concatenating their numerals. For example, the concatenation of 1, 234, and 5678 is 12345678. The value of the result depends on the numeric base, which is typically understood from context.

How do you combine integers and strings?

If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.


1 Answers

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.

like image 182
Mooing Duck Avatar answered Sep 17 '22 12:09

Mooing Duck