C Program to Round an Integer to Next Lower Multiple of 2 using Bitwise

This C Program uses bitwise operations to round(floor of) an integer to next lower multiple of 2.

Here is source code of the C Program to use bitwise operations to round(floor of) an integer to next lower multiple of 2. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* 
  2.  * C Program to use Bitwise Operations to Round(floor of) an Integer 
  3.  * to next Lower Multiple of 2
  4.  */
  5. #include <stdio.h>
  6.  
  7. void main()
  8. {
  9.     int x = 1, i, n;
  10.  
  11.     printf("enter the number :");
  12.     scanf("%d", &n);
  13.     /* for positive values */
  14.     if (n > 0)
  15.     {
  16.         for (; x <= n >> 1;)
  17.         {
  18.             x = x << 1;
  19.         }
  20.         n = x;
  21.     }
  22.     /* for negative values */
  23.     else
  24.     {
  25.         n = ~n;
  26.         n = n + 1;
  27.         for (; x <= n >> 1;)
  28.         {
  29.             x = x << 1;
  30.         }
  31.         x = x << 1;
  32.         x = ~x;
  33.         x = x + 1;
  34.         n = x;
  35.     }
  36.     printf("%d", n);
  37. }

$ cc bit10.c
$ a.out
enter the number :9
8
$ a.out
enter the number :44
32
$ a.out
enter the number :-20
-32
$ a.out
enter the number :-84
-128

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.