-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added new genutils.bits package for bitwise operations
- Loading branch information
Showing
1 changed file
with
18 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |