問題出在標題我猜。這是一個慣用的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