Saturday 11 November 2017

C Program to use Bitwise Operations to Round(floor of) an Integer to next Lower Multiple of 2


Code:

#include stdio.h>

void main()
{
    int x = 1, i, n;

    printf("enter the number :");
    scanf("%d", &n);
    /* for positive values */
    if (n > 0)
    {
        for (; x <= n >> 1;)
        {
            x = x << 1;
        }
        n = x;
    }
    /* for negative values */
    else
    {
        n = ~n;
        n = n + 1;
        for (; x <= n >> 1;)
        {
            x = x << 1;
        }
        x = x << 1;
        x = ~x;
        x = x + 1;
        n = x;
    }
    printf("%d", n);
}

Output:

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


More C Programs:









100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...