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

前端 未结 7 1845
别那么骄傲
别那么骄傲 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条回答
  •  Happy的楠姐
    2021-01-31 22:22

    I don't think it's the case that 1<<32 wraps (otherwise, why doesn't 2<<31 also wrap?), instead I think that internally modulus 32 is applied to the second operator, so that 1<<32 is actually equivalent to 1<<0. Also, consider changing the parameters types from "int" to "unsigned int". To get the value of "ones" without running into the "1<<32" problem, you can do this:

    unsigned int ones = (0xffffffff >> (32-numbits)) << at;
    

    I don't believe there are any "standard" methods for this kind of operation. I'm sure there are other ways of using bitwise operators in different ways to achieve the same outcome, but your algorithm is as good as any.

    Having said that, though, maintainability and documentation is also important. Your function would benefit from the algorithm being documented with a comment, especially to explain how you use the bitwise XOR -- which is clever, but not easy to understand at first glance.

提交回复
热议问题