Skip to content

Instantly share code, notes, and snippets.

@Packetslave
Last active December 29, 2015 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Packetslave/7712590 to your computer and use it in GitHub Desktop.
Save Packetslave/7712590 to your computer and use it in GitHub Desktop.
Bitwise operations in Python
import unittest
def lsb(i):
"""Return the position of the first (lowest) bit that's set."""
if not i:
return 0
count = 1
while i:
if i & 0x1:
return count
i = i >> 1
count += 1
return 0
def popcount(i):
"""Return the number of bits that are set."""
if not i:
return 0
count = 0
while i:
if i & 0x1:
count += 1
i = i >> 1
return count
class LsbTest(unittest.TestCase):
def testLsb(self):
# 4321
self.assertEqual(0, lsb(0)) # 0000
self.assertEqual(1, lsb(1)) # 0001
self.assertEqual(2, lsb(2)) # 0010
self.assertEqual(1, lsb(3)) # 0011
self.assertEqual(3, lsb(4)) # 0100
class PopCountTest(unittest.TestCase):
def testPopCount(self):
self.assertEqual(0, popcount(0)) # 0000
self.assertEqual(1, popcount(1)) # 0001
self.assertEqual(1, popcount(2)) # 0010
self.assertEqual(2, popcount(3)) # 0011
self.assertEqual(1, popcount(4)) # 0100
self.assertEqual(2, popcount(5)) # 0101
self.assertEqual(2, popcount(6)) # 0110
self.assertEqual(3, popcount(7)) # 0111
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment