Dynamic left or right shift

I have a pretty simple question. Is there a way to dynamically shift bitwise to the left OR to the right, for example. depending on the sign of int.

signed int n = 3; signed int m = -2; int number1 = 8; int number2 = 8; //number1 shift n; //number2 shift m; 

In this case, I want to shift the number 1 by 3 bits to the left, and the number2 - by 2 bits to the right. Is there a way without if else ?

0
source share
5 answers

Does it calculate ?: Like if-else ?

 int x = (n > 0) ? (number1 << n) : (number1 >> (-n)); int y = (m > 0) ? (number2 << n) : (number2 >> (-m)); 
+2
source

For 32 bits:

x = ((long long) x) <32) → (32 - n)

+4
source
 #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

+3
source

No, you will need a conditional.

Bitwise shift operators have undefined behavior if you use a negative value on the right.

+2
source

If the number of bits shifted is negative, the result will be undefined. However, you can experiment with your compiler, perhaps your compiler will move in the opposite direction. And of course, you can use ?: , But this is another way of expressing if-else.

0
source

All Articles