# bit_of_a_number_v1.c

Aug 16th, 2020
164
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*
2.
3.     bit_of_a_number_v1.c
4.
5.     https://www.geeksforgeeks.org/binary-representation-of-a-given-number/
6.
7.     C library function pow()
8.     https://www.tutorialspoint.com/c_standard_library/c_function_pow.htm
9.
10.     Writing a Custom Power Function
11.     https://www.edureka.co/blog/power-function-in-c/
12.
13.
14.     You can find all my C programs at Dragan Milicev's pastebin:
15.
16.     https://pastebin.com/u/dmilicev
17.
18. */
19.
20. #include <stdio.h>
21. #include <math.h>       // required for the math function pow()
22.
23. // Return base^exponent i.e. x^y. No need for #include <math.h>
24. int power(int base, int exponent)
25. {
26.     int result=1;
27.
28.     for (exponent; exponent>0; exponent--)
29.     {
30.         result = result * base;
31.     }
32.     return result;
33. }
34.
35. // Returns a bit of number n
36. /*
37. How to check whether its i-th bit is 0(OFF) or 1(ON) by
38. bitwise ANDing it with 2^i (2 raise to i).
39. 1) Let us take number 'NUM' and we want to check whether it's 0th bit is ON or OFF
40.     bit = 2 ^ 0 (0th bit)
41.     if  NUM & bit == bit means 0th bit is ON else 0th bit is OFF
42. 2) Similarly if we want to check whether 5th bit is ON or OFF
43.     bit = 2 ^ 5 (5th bit)
44.     if NUM & bit == bit means its 5th bit is ON else 5th bit is OFF.
45. */
46. int bit_of_a_number(int bit, unsigned n)
47. {
48.     //if  ( (n & (int)pow(2,bit)) == 0)     // requires #include <math.h>
49.     if  ( (n & power(2,bit)) == 0)          // no need for #include <math.h>
50.         return 0;
51.     else
52.         return 1;
53. }
54.
55. int main(void)
56. {
57.     int i, n;
58.
59.     for(n=0; n<25; n++)
60.     {
61.         printf("\n n = %2d = ", n);
62.
63.         for(i=7; i>=0; i--)
64.         {
65.             printf("%d", bit_of_a_number(i,n));
66.         }
67.
68.         printf("\n");
69.     }
70.
71.     return 0;
72.
73. } // main()
74.
RAW Paste Data Copied