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 decn");
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');
}