Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- binary_representation_of_a_number_v1.c
- https://www.geeksforgeeks.org/binary-representation-of-a-given-number/
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- // Representation of a given number, iterative method
- /*
- How to check whether its i-th bit is 0(OFF) or 1(ON) by
- bitwise ANDing it with ā2^iā (2 raise to i).
- 1) Let us take number 'NUM' and we want to check whether it's 0th bit is ON or OFF
- bit = 2 ^ 0 (0th bit)
- if NUM & bit == bit means 0th bit is ON else 0th bit is OFF
- 2) Similarly if we want to check whether 5th bit is ON or OFF
- bit = 2 ^ 5 (5th bit)
- if NUM & bit == bit means its 5th bit is ON else 5th bit is OFF.
- */
- void bin_iterative(unsigned n)
- {
- unsigned i, k=0;
- for (i=1<<31; i>0; i=i/2)
- {
- if(k>7)
- {
- printf(" ");
- k=0;
- }
- k++;
- //(n & i) ? printf("1") : printf("0");
- if(n & i)
- printf("1");
- else
- printf("0");
- }
- }
- // Representation of a given number, recursive
- /*
- step 1) if NUM > 1
- a) push NUM on stack
- b) recursively call function with 'NUM / 2'
- step 2)
- a) pop NUM from stack, divide it by 2 and print it's remainder.
- */
- void bin_recursive(unsigned n)
- {
- if (n > 1) // step 1
- bin_recursive(n/2);
- printf("%d", n%2); // step 2
- }
- // Representation of a given number, recursive using bitwise operator
- /*
- step 1: Check n > 0
- step 2: Right shift the number by 1 bit and recursive function call
- step 3: Print the bits of number
- */
- void bin_recursive_using_bitwise_operator(unsigned n)
- {
- if (n > 1)
- bin_recursive_using_bitwise_operator(n>>1);
- printf("%d", n&1);
- }
- int main(void)
- {
- int i;
- for(i=0; i<20; i++)
- {
- printf("\n %2d = ", i);
- //bin_iterative(i);
- //bin_recursive(i);
- bin_recursive_using_bitwise_operator(i);
- }
- return 0;
- } // main()
RAW Paste Data
Copied