Skip to content

Commit bd07ac5

Browse files
committed
Fixed codec: rotate
1 parent 0c5c3f0 commit bd07ac5

2 files changed

Lines changed: 14 additions & 11 deletions

File tree

codext/binary/rotate.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,15 @@
77
- decodes file content to str (read)
88
- encodes file content from str to bytes (write)
99
"""
10-
import operator
11-
1210
from ..__common__ import *
1311

1412

1513
__examples__ = {
1614
'enc(rotate-0|rotate-8|rotate-left-8)': None,
17-
'enc(rotate1|rotate-right-1|rotate_1)': {'This is a test': "*449\x1049\x100\x10:29:"},
18-
'dec(rotate1)': {'*449\x1049\x100\x10:29:': "Thhr hr ` tdrt"},
15+
'enc(rotate1|rotate-right-1|rotate_1)': {'This is a test': "*4\xb4\xb9\x10\xb4\xb9\x10\xb0\x10:\xb2\xb9:"},
1916
'enc(rotate-left-1|rotate_left_1)': {'This is a test': "¨ÐÒæ@Òæ@Â@èÊæè"},
2017
}
21-
__guess__ = ["rotate-%s" % i for i in "12"] + ["rotate-left-%s" % i for i in "12"]
18+
__guess__ = ["rotate-%d" % i for i in range(1, 8)] + ["rotate-left-%d" % i for i in range(1, 8)]
2219

2320

2421
if PY3:
@@ -31,9 +28,11 @@ def _getn(i):
3128

3229

3330
def _rotaten(text, n=1):
34-
op = [operator.lshift, operator.rshift][n > 0]
35-
n = abs(n)
36-
return "".join(chr(op(ord(c), n)) for c in ensure_str(text))
31+
r = ""
32+
for c in ensure_str(text):
33+
b = bin(ord(c))[2:].zfill(8)
34+
r += chr(int(b[-n:] + b[:-n], 2))
35+
return r
3736

3837

3938
def rotate_encode(i):
@@ -48,5 +47,5 @@ def decode(text, errors="strict"):
4847
return decode
4948

5049

51-
add("rotate", rotate_encode, rotate_decode, r"rotate(?:[-_]?bits)?[-_]?((?:left[-_]?)?[1-7])$", entropy=1.)
50+
add("rotate", rotate_encode, rotate_decode, r"rotate(?:[-_]?bits)?[-_]?((?:(?:left|right)[-_]?)?[1-7])$", entropy=1.)
5251

docs/enc/binary.md

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,13 @@ This codec XORes each group of 4 bits of the input text with a 1-byte clock sign
141141

142142
-----
143143

144-
### Rotate/Shift N bits
144+
### Rotate N bits
145145

146-
This codec rotates N bits using the `>>` (to the right) and `<<` (to the left) operations.
146+
This codec rotates of N bits each byte of an input string.
147+
148+
!!! note "Lossless"
149+
150+
This codec does not use the "`<<`" and "`>>`" operators as it is lossy in some cases. Instead, it rotates per group of 8 bits.
147151

148152
**Codec** | **Conversions** | **Aliases** | **Comment**
149153
:---: | :---: | --- | ---

0 commit comments

Comments
 (0)