Actually barrel-shift
authorStefano Rivera <stefano@rivera.za.net>
Sat, 17 May 2014 15:16:20 +0000 (17:16 +0200)
committerStefano Rivera <stefano@rivera.za.net>
Sat, 17 May 2014 15:16:20 +0000 (17:16 +0200)
naja/player.py
naja/tests/test_player.py

index b471c625135d4aea0d58af975a86e0a59e81c2a8..d4ff73211a54db98354f18c55c02fa5557e9a918 100644 (file)
@@ -50,11 +50,12 @@ class PlayerBits(object):
             self.toggle_bit(bit)
 
     def shift_bits_left(self, shift):
-        self.bits <<= shift
+        wrap = self.bits >> (8 - shift)
+        self.bits = (self.bits << shift & 0xff | wrap)
 
     def shift_bits_right(self, shift):
-        self.bits >>= shift
-
+        wrap = self.bits << (8 - shift) & 0xff
+        self.bits = (self.bits >> shift | wrap)
 
 class Player(object):
     """
index 2e17379213db3d9e4a8f5f6d0603c199ddf88eb8..07583b3bf11a312bdefed1c267f623b069b42c18 100644 (file)
@@ -85,6 +85,22 @@ class TestPlayerBits(TestCase):
         bits.toggle_bits([BITS.NORTH, BITS.BLUE, BITS.MSB])
         self.assertEqual(bits._bits, 0x92)
 
+    def test_shift_bits_left(self):
+        bits = PlayerBits(0x03)
+        self.assertEqual(bits._bits, 0x03)
+        bits.shift_bits_left(1)
+        self.assertEqual(bits._bits, 0x06)
+        bits.shift_bits_left(6)
+        self.assertEqual(bits._bits, 0x81)
+
+    def test_shift_bits_right(self):
+        bits = PlayerBits(0x06)
+        self.assertEqual(bits._bits, 0x06)
+        bits.shift_bits_right(1)
+        self.assertEqual(bits._bits, 0x03)
+        bits.shift_bits_right(1)
+        self.assertEqual(bits._bits, 0x81)
+
 
 class TestPlayer(TestCase):
     def test_new_player(self):