在C语言中,以二进制形式输出数字主要有以下两种方法:
使用`%b`格式化输出(推荐) C99标准新增了`%b`格式化说明符,可以直接将十进制整数转换为二进制字符串输出。示例如下:
```c
include int main() {
int num = 10;
printf("The binary representation of %d is %bn", num, num);
return 0;
}
```
运行结果:`The binary representation of 10 is 1010`。
手动实现二进制转换(兼容性更广)
int main() {
int num = 10;
printf("The binary representation of %d is %bn", num, num);
return 0;
}
```
运行结果:`The binary representation of 10 is 1010`。
手动实现二进制转换(兼容性更广)
若需兼容旧版C标准(不支持`%b`),可通过短除法或库函数`itoa`手动转换。例如:
- 短除法: 通过不断除以2并记录余数,逆序输出二进制位。 - `itoa`函数
注意事项:
`%b`仅适用于C99及以上标准,旧版编译器需采用其他方法。- 若输出固定长度的二进制数(如8位),可结合`%08b`等格式说明符补零。