#include <stdio.h> typedef unsigned (*fx_t)(unsigned, int); unsigned shiftleft(unsigned val, int bits) { return val << bits; } unsigned shiftright(unsigned val, int bits) { return val >> (-bits); } unsigned shift(unsigned val, int bits) { static fx_t sshift[2] = {shiftright, shiftleft}; return sshift[bits >= 0](val, bits); } int main(void) { signed int n = 3; signed int m = -2; unsigned number1 = 8; unsigned number2 = 8; printf("%u\n", shift(number1, n)); printf("%u\n", shift(number2, m)); return 0; }
You can "see the code working" on ideone: http://ideone.com/F2vAB http://ideone.com/x1RbQ
source share