Utils package

Module contents

Utility functions used by QCLight. These are mostly math and bit manipulation functions.

qclight.utils.bitstring_to_int(bitstring, start=0, end=None)[source]

Convert a bitstring to an integer.

Parameters
  • bitstring (str) – bitstring to convert

  • start (int, default: 0) – start index of the bitstring

  • end (Optional[int], default: None) – end index of the bitstring

Returns

int – integer representation of the bitstring

qclight.utils.extract_bits(number, idx)[source]

Extracts the bits with index idx (or in the list idx) from the binary representation of number. The bits are then used to build a new number, in the order they appear in the list, big endian.

Example

extract_bits(0b1011, 0) # 1
extract_bits(0b1011, 1) # 0
extract_bits(0b1011, [1, 2, 3]) # 0b011 -> 3
extract_bits(0b1011, [3, 1, 1]) # 0b100 -> 4
Parameters
  • number (int) – number in binary where the bits are extracted from

  • idx (int | list[int]) – index or list of indexes of the bits to extract, big endian

Returns

int – a number build using the extracted bits

qclight.utils.range_fixed_bits(n_bits, fixed_bits)[source]

Loops over all the numbers from 0 to 2**n_bits with the bits in the fixed_bits indexes equal to 1.

All the indexes are considered big endian.

Example

range_fixed_bits(2, set([1])) # 0b01, 0b11
range_fixed_bits(3, set([0])) # 0b100, 0b101, 0b110, 0b111
range_fixed_bits(4, set([2, 3])) # 0b0011, 0b0111, 0b1011, 0b1111
Parameters
  • n_bits (int) – number of bits of the values to loop over

  • fixed_bits (int | set[int]) – index or list of indexes of the bits equal to 1, big endian

Yields

all numbers of length n_bits with the fixed_bits equal to 1 and

Raises

OutOfRangeError – if the control_bits indexes are not valid

Return type

Iterator[int]

qclight.utils.range_fixed_bits_switch(n_bits, fixed_bits, switch_bit)[source]

Loops over all the numbers from 0 to 2**n_bits with the bits in the fixed_bits indexes equal to 1.

Each iteration of the loop will return a pair of number. The first one will have the bit in the switch_bit position equal to 0. The same bit will be 1 in the second element of the pair.

All the indexes are considered big endian.

Example

range_fixed_bits_switch(3, set([0]), 1) # (0b100, 0b110), (0b101, 0b111)
range_fixed_bits_switch(4, set([2, 3]), 1) # (0b0011, 0b0111), (0b1011, 0b1111)
range_fixed_bits_switch(5, set([0, 1, 2]), 4) # (0b11100, 0b11101), (0b11110, 0b11111)
Parameters
  • n_bits (int) – number of bits of the values to loop over

  • fixed_bits (int | set[int]) – index or list of indexes of the bits equal to 1, big endian

  • switch_bit (int) – index of the bit equal to 0/1 in the pairs, big endian

Yields

all possible pairs of numbers of length n_bits with the fixed_bits equal to 1 and the switch_bit equal to 0/1

Raises

OutOfRangeError – if the fixed_bits or switch_bit indexes are not valid

Return type

Iterator[tuple[int, int]]