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 example, given the destination integer 0xdeadbeef and the source integer 0xabcd, the idea would be to get a result of 0xabcdbeef (given a destination position of 16 bits) or 0xdeabcdef (given a destination position of 8 bits).
With the arbitrary limitation of avoiding conditionals or loops (allowing myself to use just mathematical/bitwise operations), I developed the following function (C++)
int setbits(int destination, int source, int at, int numbits)
{
int ones = ((1<<(numbits))-1)<<at;
return (ones|destination)^((~source<<at)&ones);
}
where at is the place where the source bits should be copied into the destination number (0-31) and numbits is the number of bits being copied from source (1-32). As far as I can tell, this algorithm works for all values except for at = 0 and numbits = 32 (the case when the entire destination integer is being overwritten by the source integer) due to the fact that 1<<32 results in 1 (since the shift wraps around) as opposed to 0.
My questions are:
- How is this normally done? Are there any particularly notable algorithms used (by notable, I’m asking if there are any particularly efficient tricks that can be used to do this)?
- Does my algorithm work as well as I think it does (that is, works for all values except at = 0 and numbits = 32)?
- Related to 1), is there any way to do this only using mathematical/bitwise operators? The algorithm for all values is trivial using conditions or loops, so I’m not interested in that.
Algorithm design is usually a weak point for me, so I have no idea whether or not my algorithm is ‘as good as it gets’ when only using mathematical/bitwise operations. Thanks
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:
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.