问题出在标题我猜。这是一个惯用的C方式将long转换为二进制(char *)表示形式吗?
这是我想出了一个临时的解决方案,但我想知道:
- 如果有缺点表示二进制为char *。有没有更好的方法(考虑我想要位移等的能力......)
- 如果在下面的代码中存在明显的非惯用C(或其他错误)。
所有的建议表示欢迎...
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
/* compile with
gcc -lm -std=c99
*/
void binary_repr(unsigned long input) {
int needed_digits = (int) (floor(log2(input)) + 1);
char *ptr_binarray = malloc((needed_digits + 1) * sizeof (char));
int idx = (needed_digits);
if (ptr_binarray == NULL) {
printf("Unable to allocate memory.");
exit(1);
}
else {
do {
idx--;
if (input % 2 == 0) {
ptr_binarray[idx] = '0';
}
else {
ptr_binarray[idx] = '1';
}
input = input/2;
} while (input > 0);
ptr_binarray[needed_digits] = '\0';
printf("%s\n", ptr_binarray);
free(ptr_binarray);
ptr_binarray = NULL;
}
}
int main()
{
binary_repr(8);
binary_repr(14);
binary_repr(4097);
return 0;
}
'x * sizeof(char)'可以只是'x',因为'sizeof(char)'是1的定义。 – 2009-08-10 02:17:42
我不会称之为“惯用”的东西那么大:) – qrdl 2009-08-10 06:47:36