在 C 語言中列印數字的二進位制

二進位制數制

\$\$
(6)_{10} = (110)_2
\$\$

轉換過程

6/2 = 3 0
3/2 = 1 1
1/2 = 0 1

`1` 是最高有效位 (MSB)，`0` 是最低有效位 (LSB)。因此，`6` 的二進位制是 `110`

轉換的 C 實現

C 語言中有多種方法可以將數字轉換為二進位制數系統。它可以是迭代解決方案或遞迴解決方案。

1. `number` 放在堆疊上
2. 遞迴呼叫 `number/2` 函式
3. 從堆疊中取出一個 `number`，將其除以二，然後輸出餘數。
``````#include <stdio.h>

void convertToBinary(unsigned a)
{
/* step 1 */
if (a > 1)
convertToBinary(a / 2);

/* step 2 */
printf("%d", a % 2);
}
int main() {
// Write C code here
printf("Binary of the number is: ");
convertToBinary(6);
printf("\n");

return 0;
}
``````

``````Binary of the number is: 110
``````

1. 檢查是否 `number > 0`
2. 將右移運算子應用 1 位，然後遞迴呼叫該函式。
3. 輸出 `number` 的位
``````#include <stdio.h>
void convertToBinary(unsigned n)
{
if (n > 1)
convertToBinary(n >> 1);

printf("%d", n & 1);
}
int main() {
// Write C code here
printf("Binary of the number is: ");
convertToBinary(8);
printf("\n");

return 0;
}
``````

``````Binary of the number is: 1000
``````

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.