Function to check bit value in position - C Operator

C examples for Operator:Bit Operator

Introduction

Have the function return 1 if that particular bit position is 1, and have it return 0 otherwise. Test the function in a program.

Demo Code

#include <stdio.h>
#include <limits.h>

#define CLEARINPUT while (getchar() != '\n') continue

int checkbit(int value, int position);

int main(void)
{
  int value, position, ch;

  printf("Enter an integer: ");
  while (scanf("%d", &value) == 1){
    printf("Enter a position: ");
    while (scanf("%d", &position) == 1){
      printf("Position %d of %d is %d\n", position, value,checkbit(value, position));
      printf("Enter a position: ");
    }//www.  j  a  v  a 2  s .co m
    CLEARINPUT;
    printf("\nEnter an integer: ");
  }
  return 0;
}
// return the state of the bit in the given position of the integer value
int checkbit(int value, int position){
  value >>= (position - 1);
  return value & 1;
}

Result


Related Tutorials