Doug
Doug

Reputation: 11

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

I checked out the SWAR algorithm (SIMD Within A Register) for reversing bit order of unsigned ints. Is there something similar for signed int?

Upvotes: 0

Views: 1489

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283753

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.

Upvotes: 1

Lindydancer
Lindydancer

Reputation: 26124

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.

Upvotes: 0

Related Questions