Left shift only part of the number

I need to find the fastest equivalence of the following C code.

int d = 1 << x; /* d=pow(2,x) */ int j = 2*d*(i / d) + (i % d); 

What I thought should shift the upper left 32 bits of i.
For example, the following I am with x = 5:
1010 1010 1010 1010
will become:
0101 0101 010 0 1010
Is there an assembly for this? How to quickly complete this operation?

+4
source share
5 answers

divisions are slow:

 int m = (1 << x) - 1; int j = (i << 1) - (i & m); 

Update

or probably faster:

 int j = i + (i & (~0 << x)); 
+9
source

x86 32-bit build (AT & T syntax):

 /* int MaskedShiftByOne(int val, int lowest_bit_to_shift) */ mov 8(%esp), %ecx mov $1, %eax shl %ecx, %eax ; does 1 << lowest_bit_to_shift mov 4(%esp), %ecx dec %eax ; (1 << ...) - 1 == 0xf..f (lower bitmask) mov %eax, %edx not %edx ; complement - higher mask and %ecx, %edx ; higher bits and %ecx, %eax ; lower bits lea (%eax, %edx, 2), %eax ; low + 2 * high ret 

This should work on both Linux and Windows.

Edit: i + (i & (~0 << x)) shorter:

 mov 4(%esp), %ecx mov $-1, %eax mov 8(%esp), %edx shl %edx, %eax and %ecx, %eax add %ecx, %eax ret 

Moral: Never start assembly. If you really need it, parse the highly optimized compiler output ...

+5
source

Shift one upper bit x left.

 unsigned i = 0xAAAAu; int x = 5; i = (i & ((1 << x) - 1)) | ((i & ~((1 << x) - 1)) << 1); // 0x1554A; 

Some explanations:

(1 << x) - 1 makes the mask the upper zero bit of 32 - x .

~((1 << x) - 1) makes the mask equal to zero x bits.

After the bit is zeroed, we shift the upper part and or them together.

Try this on Codepad .

+4
source
 int m = (1 << x) - 1; int j = ((i & ~m) << 1) | (i & m); 

There is no build command to do what you want, but the solution I give is faster because it avoids separation.

+3
source

Intel Syntax:

 mov ecx,[esp+4] ;ecx = x mov eax,[esp+8] ;eax = i ror eax,cl inc cl clc rcl eax,cl ret 

Morality: highly optimized compiler output ... no.

+1
source

All Articles