Advertisement
93aef0ce4dd141ece6f5

dec2bin

Jan 31st, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. /*
  6.  * maximum bit size
  7.  * for different
  8.  * sizes of numbers
  9.  */
  10. #define MAX_BITS 32
  11.  
  12. /*
  13.  * check to see if the
  14.  * given bit is set (1)
  15.  * or not (0)
  16.  */
  17. int is_bit (int i) {
  18.     return i & 0x01;
  19. }
  20.  
  21. /*
  22.  * bit shift each bit
  23.  * in number and check
  24.  * if bit is set (1) or
  25.  * not (0) and put into
  26.  * array
  27.  */
  28. void dec_to_bin (int n, char *buf) {
  29.     int i;
  30.     for (i = 0; i < MAX_BITS; i++) {
  31.         buf[MAX_BITS-i-1] = (is_bit (n >> i)) ? '1' : '0';
  32.     }
  33. }
  34.  
  35. /*
  36.  * print bits with
  37.  * iteration
  38.  */
  39. int print_bits (const char *buf) {
  40.     int i;
  41.     for (i = 0; i < MAX_BITS; i++) {
  42.         if (i != 0 && i % 8 == 0) {
  43.             putchar (' ');
  44.         }
  45.         putchar (buf[i]);
  46.     }
  47.     putchar ('\n');
  48.  
  49.     return i;
  50. }
  51.  
  52. int main (int argc, char *argv[]) {
  53.     char buf[MAX_BITS];
  54.     memset (buf, '0', MAX_BITS);
  55.  
  56.     dec_to_bin (atoi (argv[1]), buf);
  57.  
  58.     printf ("%d to bits: ", atoi (argv[1]));
  59.  
  60.     print_bits (buf);
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement