C Program to Find MSB Position using Function

This C Program uses function to return the MSB position of unsigned integer.

Here is source code of the C Program use function to return the MSB position of unsigned integer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program that uses Function to return MSB position of unsigned Integer
  3.  */
  4. #include <stdio.h>
  5. #define NUM_BITS_INT 32
  6. int int_msb_position(int n);
  7.  
  8. void main()
  9. {
  10.     int n, pos;
  11.  
  12.     printf("Enter a number : ");
  13.     scanf("%d", &n);
  14.     pos = int_msb_position(n);
  15.     printf("\nPosition of MSB bit = %d\n", NUM_BITS_INT - (pos + 1));
  16. }
  17.  
  18. /* Function to find the MSB bit position */
  19. int int_msb_position(int n)
  20. {
  21.     int i = 0, bit;
  22.     while (i < NUM_BITS_INT)
  23.     {
  24.         bit = n & 0x80000000;
  25.         if (bit == -0x80000000)
  26.            {
  27.             bit = 1;
  28.         }
  29.            if (bit == 1) 
  30.             break;
  31.         n = n << 1;
  32.         i++;
  33.     }
  34.     return i;
  35. }

$ cc bit24.c
$ a.out
Enter a number : 127
 
Position of MSB bit = 6
 
Enter a number : 259
 
Position of MSB bit = 8
 
Enter a number : 5
 
Position of MSB bit = 2

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.