如何在C中连接两个整数 [英] How to concatenate two integers in C
问题描述
Stack Overflow 用许多其他语言回答了这个问题,但没有用 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.
C 中如何将两个整数连接起来?
示例:
x = 11;
y = 11;
我希望 z 如下:
z = 1111;
其他示例尝试使用字符串执行此操作.没有字符串的方法是什么?
Other examples attempt to do this with strings. What is a way to do this without strings?
我正在寻找一种在 C 中执行此操作的有效方法,因为在我的特定用法中,这是代码的时间关键部分.
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.
提前致谢!
推荐答案
unsigned concatenate(unsigned x, unsigned y) {
unsigned pow = 10;
while(y >= pow)
pow *= 10;
return x * pow + y;
}
我避免使用 log10
和 pow
函数,因为我很确定它们使用浮点并且速度很慢,所以这 可能在您的机器上更快.或许.个人资料.
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.
这篇关于如何在C中连接两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!