Skip to content

Commit 5d964a0

Browse files
improved documentation and test
1 parent fda6145 commit 5d964a0

1 file changed

Lines changed: 13 additions & 12 deletions

File tree

electricpy/compute.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,14 @@ def string_to_bits(str):
253253
254254
Converts a Pythonic string to the string's binary representation.
255255
256+
Examples
257+
--------
258+
>>> from electricpy import compute as cmp
259+
>>> cmp.string_to_bits("A")
260+
'01000001'
261+
>>> cmp.string_to_bits("Hello")
262+
'0000010010001100101110110011011001101111'
263+
256264
Parameters
257265
----------
258266
str: string
@@ -266,18 +274,11 @@ def string_to_bits(str):
266274
"""
267275
data = ''.join(format(ord(x), 'b') for x in str)
268276

269-
# If empty, return as-is
270-
if len(data) == 0:
271-
return data
272-
273-
# If length is already a power of two, return unchanged
274-
n = len(data)
275-
if n & (n - 1) == 0:
276-
return data
277+
# Pad to Nearest Byte
278+
offset = len(data) % 8
279+
if offset != 0:
280+
data = (8 - offset) * '0' + data
277281

278-
# Compute next power of two and pad with leading zeros
279-
next_pow = 1 << n.bit_length()
280-
pad_len = next_pow - n
281-
return '0' * pad_len + data
282+
return data
282283

283284
# END

0 commit comments

Comments
 (0)