An interesting problem I\'ve been pondering the past few days is how to copy one integer\'s bits into another integer at a given position in the destination integer. So, for exa
I don't think it can be done more efficient unless you write assembler.
You can improve the readability and solve your overflow problem changing some little things:
int setbits2(int destination, int source, int at, int numbits)
{
// int mask = ((1LL<>(sizeof(int)*8-numbits))<
More efficient assembler version (VC++):
// 3rd aproach
#define INT_SIZE 32;
int setbits3(int destination, int source, int at, int numbits)
{ __asm {
mov ecx, INT_SIZE
sub ecx, numbits
or eax, -1
shr eax, cl
mov ecx, at
shl eax, cl // mask == eax
mov ebx, eax
not eax
and eax, destination
mov edx, source
shl edx, cl
and edx, ebx
or eax, edx
}}