dmilicev

binary_representation_of_a_number_v1.c

Aug 16th, 2020
1,428
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3.     binary_representation_of_a_number_v1.c
  4.  
  5.     https://www.geeksforgeeks.org/binary-representation-of-a-given-number/
  6.  
  7.  
  8.     You can find all my C programs at Dragan Milicev's pastebin:
  9.  
  10.     https://pastebin.com/u/dmilicev
  11.  
  12. */
  13.  
  14. #include <stdio.h>
  15.  
  16. // Representation of a given number, iterative method
  17. /*
  18. How to check whether its i-th bit is 0(OFF) or 1(ON) by
  19. bitwise ANDing it with ā€œ2^iā€ (2 raise to i).
  20. 1) Let us take number 'NUM' and we want to check whether it's 0th bit is ON or OFF
  21.     bit = 2 ^ 0 (0th bit)
  22.     if  NUM & bit == bit means 0th bit is ON else 0th bit is OFF
  23. 2) Similarly if we want to check whether 5th bit is ON or OFF
  24.     bit = 2 ^ 5 (5th bit)
  25.     if NUM & bit == bit means its 5th bit is ON else 5th bit is OFF.
  26. */
  27. void bin_iterative(unsigned n)
  28. {
  29.     unsigned i, k=0;
  30.  
  31.     for (i=1<<31; i>0; i=i/2)
  32.     {
  33.         if(k>7)
  34.         {
  35.             printf(" ");
  36.             k=0;
  37.         }
  38.         k++;
  39.  
  40.         //(n & i) ? printf("1") : printf("0");
  41.         if(n & i)
  42.             printf("1");
  43.         else
  44.             printf("0");
  45.     }
  46. }
  47.  
  48. // Representation of a given number, recursive
  49. /*
  50. step 1) if NUM > 1
  51.     a) push NUM on stack
  52.     b) recursively call function with 'NUM / 2'
  53. step 2)
  54.     a) pop NUM from stack, divide it by 2 and print it's remainder.
  55. */
  56. void bin_recursive(unsigned n)
  57. {
  58.     if (n > 1)              // step 1
  59.         bin_recursive(n/2);
  60.  
  61.     printf("%d", n%2);      // step 2
  62. }
  63.  
  64. // Representation of a given number, recursive using bitwise operator
  65. /*
  66. step 1: Check n > 0
  67. step 2: Right shift the number by 1 bit and recursive function call
  68. step 3: Print the bits of number
  69. */
  70. void bin_recursive_using_bitwise_operator(unsigned n)
  71. {
  72.     if (n > 1)
  73.         bin_recursive_using_bitwise_operator(n>>1);
  74.  
  75.     printf("%d", n&1);
  76. }
  77.  
  78.  
  79. int main(void)
  80. {
  81.     int i;
  82.  
  83.     for(i=0; i<20; i++)
  84.     {
  85.         printf("\n %2d = ", i);
  86.         //bin_iterative(i);
  87.         //bin_recursive(i);
  88.         bin_recursive_using_bitwise_operator(i);
  89.     }
  90.  
  91.     return 0;
  92.  
  93. } // main()
  94.  
RAW Paste Data Copied