我正在尝试将整数10转换为二进制数1010.
这段代码尝试了,但我在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);
}
Run Code Online (Sandbox Code Playgroud)
如何在C中将整数转换为二进制?
pmg*_*pmg 15
如果要将数字转换为另一个数字(不是数字到字符串),并且您可以使用小范围(0到1023用于具有32位整数的实现),则无需添加char*到解决方案
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);
}
Run Code Online (Sandbox Code Playgroud)
HalosGhost建议将代码压缩成一行
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
Run Code Online (Sandbox Code Playgroud)
你需要初始化bin,例如
bin = malloc(1);
bin[0] = '\0';
Run Code Online (Sandbox Code Playgroud)
或使用calloc:
bin = calloc(1, 1);
Run Code Online (Sandbox Code Playgroud)
你这里也有一个错误:
bin = (char *)realloc(bin, sizeof(char) * (sizeof(bin)+1));
Run Code Online (Sandbox Code Playgroud)
这需要是:
bin = (char *)realloc(bin, sizeof(char) * (strlen(bin)+1));
Run Code Online (Sandbox Code Playgroud)
(即使用strlen,而不是sizeof).
而且你应该增加大小之前调用strcat的.
而且你没有释放bin,所以你有内存泄漏.
并且你需要0,1转换为'0', '1'.
并且你不能将字符串strcat到字符串.
除此之外,它很接近,但代码应该更像这样(警告,未经测试!):
int int_to_bin(int k)
{
char *bin;
int tmp;
bin = calloc(1, 1);
while (k > 0)
{
bin = realloc(bin, strlen(bin) + 2);
bin[strlen(bin) - 1] = (k % 2) + '0';
bin[strlen(bin)] = '\0';
k = k / 2;
}
tmp = atoi(bin);
free(bin);
return tmp;
}
Run Code Online (Sandbox Code Playgroud)
只需使用itoa转换为字符串,然后使用atoi转换回十进制.
unsigned int_to_int(unsigned int k) {
char buffer[65]; /* any number higher than sizeof(unsigned int)*bits_per_byte(8) */
return atoi( itoa(k, buffer, 2) );
}
Run Code Online (Sandbox Code Playgroud)