I checked out the SWAR algorithm (SIMD Within A Register) for reversing bit order of unsigned int
s. Is there something similar for signed int
?
Signed INT Conversion of MSB ->LSB and LSB->MSB in C++
1.3k views Asked by Doug At
2
There are 2 answers
0
On
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.
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.