开发者

Signed INT Conversion of MSB ->LSB and LSB->MSB in C++

开发者 https://www.devze.com 2023-02-24 04:25 出处:网络
I check开发者_Go百科ed out the SWAR algorithm (SIMD Within A Register) for reversing bit order of unsigned ints. Is there something similar for signed int?The algorithm only works on unsigned integers

I check开发者_Go百科ed out the SWAR algorithm (SIMD Within A Register) for reversing bit order of unsigned ints. Is there something similar for signed int?


The algorithm only works on unsigned integers, since sign-extension during bit-shifting is not wanted.

Since the algorithm uses only the binary representation, not the numeric value, you can just cast to an unsigned integer of equal size (it will have identical representation), use the algorithm, and cast back to signed. These conversions won't turn into any assembly instructions, they just cause the compiler to produce logical shift right instead of arithmetic shift right.


It depends on what you mean by reversing the bits of a signed integer. However, in general, if you plan to place the sign bit in the LSB position and the LSB in the sign bit (which is the normal way to swap anything) then the same algoritm could be used for both signed and unsigned integers.

If this isn't the case, please explain what you mean by reversing a signed integer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号