How to concatenate two integers in C

后端 未结 9 1289
执念已碎
执念已碎 2020-11-29 11:27

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 t

9条回答
  •  旧巷少年郎
    2020-11-29 11:34

    Here is a variation of @Mooing Duck's answer that uses a lookup table for multiples of 10 (for platform's with slow integer multiply) It also returns unsigned long long to allow for larger values and uses unsigned long long in the lookup table to account for @chqrlie's comment about infinite loops. If the combined inputs can be guaranteed to not exceed unsigned, those could be changed.

    static const unsigned long long pow10s[] = {
       10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000
    };
    unsigned long long concat(unsigned x, unsigned y) {
        const unsigned long long *p = pow10s;
        while (y >= *p) ++p;
        return *p * x +y;        
    }
    

提交回复
热议问题