BitShuffle#
The BitShuffle class provides a method for shuffling bits in integers by combining the functionalities of the BitPermutation and BitInversion classes. The shuffling operation is performed by first applying a permutation to rearrange the bits, followed by an inversion to flip some of them.
Constructors#
__init__#
__init__(self,
permutation: BitPermutation | None = None,
inversion: BitInversion | None = None,
)
Initializes a BitShuffle object with a specified permutation and inversion. If no permutation or inversion is provided, the identity permutation and inversion are used.
generate_random#
BitShuffle.generate_random(length: int)
Generates a random shuffle of a specified length.
from_tuple#
BitShuffle.from_tuple(cls, data: tuple[int, ...])
Creates a shuffle from a tuple of integers, where the tuple represents a shuffle generated by the as_tuple() method.
unpack#
BitShuffle.unpack(number: int)
Restores the shuffle from a packed integer, which should be obtained using the pack() method.
Properties#
len#
Returns the length of the shuffle in bits.
permutation#
@property
permutation() -> BitPermutation
Returns the permutation used in the shuffle.
inversion#
@property
inversion() -> BitInversion
Returns the inversion used in the shuffle.
is_identity#
is_identity() -> bool
Checks if the shuffle is the identity transformation, meaning no bits are moved or inverted.
Transformations#
shuffle#
shuffle(x: int) -> int
Applies the permutation and bit inversion to the input integer x and returns the result.
unshuffle#
unshuffle(x: int) -> int
Applies the inverse permutation and bit inversion to the input integer x, returning the original value.
Generators#
shuffle_iter(self, s: Iterable[int]) -> Generator[int, int, None]
unshuffle_iter(self, s: Iterable[int]) -> Generator[int, int, None]
Applies the shuffle or unshuffle function to each element in the input iterable s. The result is a generator that yields integers with shuffled or unsuffled bits.
Representations#
as_tuple#
as_tuple() -> tuple[int, ...]
Returns the shuffle as a tuple of integers.
pack#
pack() -> int
Packs the shuffle into a single integer. The packed integer can be used to restore the shuffle later using the unpack method.
Caution: the resulting integer can be very large.
Examples#
Create a random shuffle and apply it to a set of numbers:
bs = BitShuffle.generate_random(16)
assert len(bs.permutation) == 16
assert len(bs.inversion) == 16
assert len(bs) == 16
for x in (-123, -1, 0, 1, 123, 2009, 314159265358979323846):
y = bs.shuffle(x)
z = bs.unshuffle(y)
assert z == x
packed = bs.pack()
print(packed) # e.g., 2457135333419351350929424
recovered = BitShuffle.unpack(packed)
assert recovered == bs