0

For bitshifting large integers. I have seen this answer in StackOverflow:

uint64_t i1, i2, i3, o1, o2, o3; // {o3, o2, o1} = {i3, i2, i1} << 3;

o3 = i3 << 3 | i2 >> (32 - 3);
o2 = i2 << 3 | i1 >> (32 - 3);
o1 = i1 << 3;

But, this only works for maximum 32 left bit-shifts. How can I create a solution with n-bits left shifts? Needs to be constant time.

einstein
  • 13,389
  • 27
  • 80
  • 110
  • Most obvious would be `switch(shift / 32)` and the solution you presented with variants for larger shifts. There is probably a trickier solution with arrays, but I doubt it would be optimal. – zch Mar 26 '20 at 21:24
  • yeah was thinking about something like this. – einstein Mar 26 '20 at 21:50
  • are {i3, i2, i1} 32-bit or 64-bit values? in the linked question, the question is about "unsigned int" values representing the limbs of the larger integer. If the i values are holding 64-bits, then you'll want (64 - shift) instead. – Vincent Lucarelli Mar 27 '20 at 13:49
  • @VincentLucarelli yeah true. – einstein Mar 27 '20 at 17:48
  • Now, I know why it was 64 bit values. clang and gcc treats bit shifting differently when overflowed. On gcc it becomes zero if the bitshift is larger than the size of the operand. In clang, it wraps around again. To handle the clang case you need to use 64 bit sizes. – einstein Mar 27 '20 at 23:37

0 Answers0