C language decimal to binary display gadget implementation code
- 2020-04-01 23:32:17
- OfStack
Calculator in the display of binary digits, if the beginning is 0. Will not be displayed, for people in the SCM mix, this is sometimes very troublesome, so write a small tool.
The function is to enter the decimal number, and then display the 2, every 4 Spaces, can adjust the number range (multiple of 8)
If anyone can know the calculator similar to win7 under Linux, please reply and inform. Thank you very much ~
Such as:
$dec2bin 1, 135
Num 8 Binary is: 0B1000 0111
Done!
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
$dec2bin 2, 135
Num 16 Binary is: 0B0000 0000 1000 0111
Done!
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
The code is as follows:
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#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');
}