Reverse Bits
by Isai Damier

#======================================================================
# Author: Isai Damier
# Title: Reverse Bits of int (32-bit)
# Project: geekviewpoint
# Package: algorithms
#
# Statement:
#   Given an integer, reverse its bit sequence.
#
# Sample Input:  00000000000000001111111111111110
# Sample Output: 01111111111111110000000000000000
#
# Technical Details:
#   It is necessary to know whether the decimal number being passed as
#   input is of type byte (8-bit) or short (16-bit) or  (32-bit) or
#   long (64-bit): because Python will discard leading zeroes. For
#   instance, if x = 0011010, Python will trim it to 11010 and then
#   cause the reverse to look like 1011. Under such circumstances the
#   reverseBits operation would not be reversible.
#
#   To keep things simple, the presented algorithm treats  (32-bit)
#   inputs.
#====================================================================== 
 def reverseBitsOfInt( x ):
  size = 32
  y = 0
  position = size - 1
  while position > 0:
    y += ( ( x & 1 ) << position )
    x >>= 1
    position -= 1

  return y
import unittest
from algorithms import bitwise as bits

class Test( unittest.TestCase ):

    def testReverseBitsOfInt( self ):
        a = "00000000000000001111111111111110"
        b = "01111111111111110000000000000000"
        x = int( a, 2 )
        r = int( b, 2 )
        self.assertEquals( r, bits.reverseBitsOfInt( x ) )
        self.assertEquals( x, bits.reverseBitsOfInt( r ) )