如何连接用C两个整数 [英] How to concatenate two integers in C
问题描述
堆栈溢出,这个问题在许多其他语言回答,而不是C.所以,我想我会问,既然我有同样的问题。
一个人怎么连接两个整数用C?
例如:
X = 11;
Y = 11;
我想ž如下:
Z = 1111;
其他的例子试图用绳子做到这一点。什么是一个办法做到这一点,而不串?
我因为在我的特定使用在寻找一种有效的方式在C中做到这一点,这是进入一个时间code的重要组成部分。
先谢谢了!
符号串连(无符号X,无符号Y){
无符号的POW = 10;
而(Y> = POW)
POW * = 10;
返回X * POW + Y;
}
我避免了日志10
和 POW
的功能,因为我是pretty确保他们使用浮点并slowish,所以这个的可能的是你的机器上速度更快。也许。个人资料。
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!
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.
这篇关于如何连接用C两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!