Implementing a shift function - C Operator

C examples for Operator:Bit Operator

Description

Implementing a shift function

Demo Code

#include <stdio.h>

int shift (int value, int n)
{
    if ( n > 0 )    // left shift
        value <<= n;/*from  w w  w . j  a  va2s . c o  m*/
    else            // right shift
        value >>= -n;

    return value;
}

int main (void)
{
    int w1 = 0177, w2 = 0454u;
    printf("%o\t%o\t\n", shift (w1, 5), w1 << 5);
    printf("%o\t%o\t\n", shift (w1, -6), w1 >> 6);
    printf("%o\t%o\t\n", shift (w2, 0), w2 >> 0);
    printf("%o\n", shift (shift (w1, -3), 3));

    return 0;
}

Result


Related Tutorials