Skip to content

Commit

Permalink
Added new genutils.bits package for bitwise operations
Browse files Browse the repository at this point in the history
  • Loading branch information
timbernat committed Jun 14, 2024
1 parent b2cf13f commit 344a34a
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions polymerist/genutils/bits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'''For bitwise operations and conversions to/from bitstrings'''

from typing import Union


def int_to_bits(n : int, num_bits : int=8, clamp : bool=False, as_list : bool=False) -> Union[str, list[int]]:
'''
Convert an integer into a string of its bits, padded out to <num_bits> bits
If clamp=True and the binary representation of <n> has more than <num_bits> bits, then leading bits will be discarded
If as_list=True, will return as list of 0/1 ints; otherwise, will return as string
'''
bitstring = f'{n:0{num_bits}b}' # format into given number of bits with leading zeros - way easier than directly implementing bitshift-based operations
if clamp:
bitstring = bitstring[-num_bits:]

if as_list:
return [int(bit) for bit in bitstring]
return bitstring

0 comments on commit 344a34a

Please sign in to comment.