Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- bit_of_a_number_v1.c
- https://www.geeksforgeeks.org/binary-representation-of-a-given-number/
- C library function pow()
- https://www.tutorialspoint.com/c_standard_library/c_function_pow.htm
- Writing a Custom Power Function
- https://www.edureka.co/blog/power-function-in-c/
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- #include <math.h> // required for the math function pow()
- // Return base^exponent i.e. x^y. No need for #include <math.h>
- int power(int base, int exponent)
- {
- int result=1;
- for (exponent; exponent>0; exponent--)
- {
- result = result * base;
- }
- return result;
- }
- // Returns a bit of number n
- /*
- 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.
- */
- int bit_of_a_number(int bit, unsigned n)
- {
- //if ( (n & (int)pow(2,bit)) == 0) // requires #include <math.h>
- if ( (n & power(2,bit)) == 0) // no need for #include <math.h>
- return 0;
- else
- return 1;
- }
- int main(void)
- {
- int i, n;
- for(n=0; n<25; n++)
- {
- printf("\n n = %2d = ", n);
- for(i=7; i>=0; i--)
- {
- printf("%d", bit_of_a_number(i,n));
- }
- printf("\n");
- }
- return 0;
- } // main()
Add Comment
Please, Sign In to add comment