i have to reverse the position of integer like this
input = 12345
output = 54321
i made this but it gives wrong output e.g 5432
#include
template <typename T>
T reverse(T n, size_t nBits = sizeof(T) * 8)
{
T reverse = 0;
auto mask = 1;
for (auto i = 0; i < nBits; ++i)
{
if (n & mask)
{
reverse |= (1 << (nBits - i - 1));
}
mask <<= 1;
}
return reverse;
}
This will reverse bits in any signed or unsigned integer (short, byte, int, long ...). You can provide additional parameter nBits to frame the bits while reversing.
i. e. 7 in 8 bit = 00000111 -> 11100000 7 in 4 bit = 0111 -> 1110