Is there any way to do 128-bit shifts on gcc <4.4?

北城余情 提交于 2019-11-27 23:59:34
janm

I'm pretty sure that __int128_t is available on earlier versions of gcc. Just checked on 4.2.1 and FreeBSD and sizeof(__int128_t) gives 16.

You could also use a library. This would have the advantage that it is portable (regarding platform and compiler) and you could easily switch to even bigger datatype. One I could recommend is gmp (even if its intention is not to handle bitwidth x, but variable as big as you want).

Bit shifting is very easy in any arbitrary number of bits. Just remember to shift the overflowed bits to the next limb. That's all

typedef struct {
   int64_t high;
   uint64_t low;
} int128_t;


int128_t shift_left(int128_t v, unsigned shiftcount)
{
   int128_t result;
   result.high = (v.high << shiftcount) | (v.low >> (64 - shiftcount));
   result.low  =  v.low  << shiftcount;
   return result;
}

Similar for shift right

int128_t shift_right(int128_t v, unsigned shiftcount)
{
   int128_t result;
   result.low  = (v.low  >> shiftcount) | (v.high << (64 - shiftcount));
   result.high =  v.high >> shiftcount;
   return result;
}

You could use two 64-bit ints, but then you need to keep track of the bits moving between.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!