Algorithm for copying N bits at arbitrary position from one int to another

前端 未结 7 1837
别那么骄傲
别那么骄傲 2021-01-31 21:36

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

7条回答
  •  野性不改
    2021-01-31 21:58

    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
    }}
    
    • 1st aproach: Slower on 32bit architecture
    • 2nd aproach: (~0u) and (sizeof(int)*8) are calculated at compile time, so they don't charge any cost.
    • 3rd aproach: You save 3 ops (memory accesses) writing it in assembler but you will need to write ifdefs if you want to make it portable.

提交回复
热议问题