c语言中十进制转二进制显示小工具的实现代码
计算器在显示二进制位数时候,如果开头是0.是不会显示的,对于在单片机混的人,这个有时候很麻烦,所以写个小工具.
功能就是输入十进制数字,然后显示出2进制,每显示4位一次空格,可以调整位数范围(8的倍数)
如果有谁能知道linux下类似win7的那个计算器,麻烦回复告知一下吧.很是感谢~
例如:
$ dec2bin 1 135
Num 8 Binary is : 0B1000 0111
done!
===============================
$ dec2bin 2 135
Num 16 Binary is : 0B0000 0000 1000 0111
done!
===============================
代码如下:
===========================================================
/*
* =======================================================================
*
* Filename: dec2bin.c
*
* Description: dec to binary show
* =======================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#define HALF_CHAR 4
void bit_print(int bit_num, int a);
int main(int argc, char **argv)
{
if (argc != 3) {
printf("use: name num dec\n");
exit(1);
}
bit_print(atoi(argv[1]),atoi(argv[2]));
printf("done!\n");
return 0;
}
void bit_print(int bit_num, int a)
{
int i;
int n = sizeof(char) * 8 * bit_num;
int mask = 1 << (n - 1);
printf("Num %d Binary is : 0B", (bit_num * 8));
for (i = 1; i <= n; ++i) {
putchar(((a & mask) == 0) ? '0' : '1');
a <<= 1;
if (i % HALF_CHAR == 0 && i < n)
putchar(' ');
}
putchar('\n');
}
栏 目:C代码
本文地址:http://www.codeinn.net/misctech/55141.html