This is a C Program to find the highest bit set for any given integer.
This C Program finds the Highest Bit Set for any given Integer.
Take input from the user and finds the highest bit set in a given integer as shown in the program below.
Here is source code of the C Program to find the Highest Bit Set for any given Integer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/* * C Program to find the Highest Bit Set for any given Integer */ #include <stdio.h> #define NUM_BITS sizeof(int)*8 int highest_bit_set(int); void display(int); int i = NUM_BITS; void main() { int num, pos; printf("\nenter the number:"); scanf("%d", &num); display(num); pos = highest_bit_set(num); printf("\nthe position of the highest bit set is %d", pos); } /* RETURNS THE POSITION */ int highest_bit_set(int num) { int count = 0; while (num >> 1 != 0) { count++; num = num >> 1; } return(count); } /* DISPLAYS THE NUMBER IN BINARY REPRESENTATION */ void display(int num) { int c; c = num & 1; if (i > 0) { i--; display(num >> 1); } printf("%d", c); }
In this C Program, we are reading the number using the ‘num’ variable. The display() function is used display the number in binary representation. Binary AND Operator is used to copy a bit to the ‘c’ variable if it exists in both operands.
If condition statement is used to check the value of ‘i’ variable value is greater than or equal to 0. If the condition is true then execute the statement and decrement the value of ‘i’ variable by 1. Recursively we call the display() function by moving the value of ‘num’ variable to right by the number of bits specified by the right operand and pass this value as an argument to the display() function.
Once the condition becomes false then print the number in binary representation. The ‘pos’ variable is used to call the highest_bit_set() function by passing the ‘num’ variable value as an argument.
While loop is used to check the condition that the left operand’s value of ‘num’ is moved right by the number of bits specified by the right operand using Binary Right shift operator value is not equal to 0. If the condition is true then execute the loop and increment the value of ‘count’ variable.
The ‘num’ variable is used to compute the Binary Right Shift operation by moving the value of ‘num’ to right by the number of bits specified by the right operand and return the value to the called variable ‘pos’. Print the position of the highest bit set value using printf statement.
$ cc bit17.c $ a.out enter the number:10000 000000000000000000010011100010000 the position of the highest bit set is 13
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Check Computer Science Books
- Check C Books
- Apply for Computer Science Internship
- Practice BCA MCQs
- Watch Advanced C Programming Videos