Replace bits from one long with bits of another
Bobb Fwed
Posts: 1,119
I need to replace an arbitrary number of bits in one long with the same number of bits from another long at a (possibly) different arbitrary position...for example:
v1 := %1001_1010_1011
v2 := %1111_0000_0101
replace 5 bits of v2 starting at bit 3 with bits of v1 starting at bit 1
result is: v2 == %1111_1010_1101
While the example is only a byte and a half, I need it to work with all 32 bits.
Here is a first stab at this, it works, but I'm looking for a faster way to do it.
v1 := %1001_1010_1011
v2 := %1111_0000_0101
replace 5 bits of v2 starting at bit 3 with bits of v1 starting at bit 1
result is: v2 == %1111_1010_1101
While the example is only a byte and a half, I need it to work with all 32 bits.
Here is a first stab at this, it works, but I'm looking for a faster way to do it.
v1 := %1001_1010_1011 v2 := %1111_0000_0101 bits := 5 ' number of bits to replace start1 := 1 ' get bits from variable 1 starting at bit 1 start2 := 3 ' put bits from variable 1 into variable 2 starting at bit 3 v1 >>= start1 ' get to starting bit v1 &= (-1 >> (32 - bits)) ' remove all other bits v1 <<= start2 ' shift to correct position v2 &= !((-1 >> (32 - bits)) << start2) ' remove bits that are being replaced v2 |= v1 ' put bits from first variable into this one ' result v2 == %1111_[I][B]1010_1[/B][/I]101
Comments
result:= v1 & mask | v2 & !mask
not tested, but in my theory it worked ;o) (of course start1,start2 and v1,v2 have the same values as in your code)
PS: Oh ... now I understand the full question .. ;o) ... cut out anywhere and put in somewhere else ... so forget about the solution given here
Better yet, since it doesn't alter v1:
-Phil
result := (v1 & mask)<<start2 | v2 & !(mask<<start2)
How's that?
But that makes it slower than Phil's second solution, which is that fastest.
Thanks guys!
There was a bug in the first version I just posted, here is the corrected one:
-Phil
But even faster yet is to assign it in-line (another 96 cycles faster):
-Phil
-Phil
Optimized a little by modifying bits: