在C中将整数转换为二进制 [英] Converting an integer to binary in C
本文介绍了在C中将整数转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将整数10转换为二进制数1010.
I'm trying to convert an integer 10 into the binary number 1010.
此代码尝试了此操作,但是我在strcat()上遇到了段错误:
This code attempts it, but I get a segfault on the strcat():
int int_to_bin(int k)
{
char *bin;
bin = (char *)malloc(sizeof(char));
while(k>0) {
strcat(bin, k%2);
k = k/2;
bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));
}
bin[sizeof(bin)-1] = '\0';
return atoi(bin);
}
如何在C语言中将整数转换为二进制?
How do I convert an integer to binary in C?
推荐答案
如果要将数字转换为另一个数字(而不是数字转换为字符串),则可以在较小的范围内实现(0到1023用于实现)使用32位整数),则无需在解决方案中添加char*
If you want to transform a number into another number (not number to string of characters), and you can do with a small range (0 to 1023 for implementations with 32-bit integers), you don't need to add char*
to the solution
unsigned int_to_int(unsigned k) {
if (k == 0) return 0;
if (k == 1) return 1; /* optional */
return (k % 2) + 10 * int_to_int(k / 2);
}
HalosGhost 建议将代码压缩为一行
HalosGhost suggested to compact the code into a single line
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
这篇关于在C中将整数转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文