qml.math.int_to_binary

int_to_binary(integer, width)[source]

Convert an integer or an array of integers to an array of bitstrings of given length, representing the integers as binaries.

Parameters:
  • integer (int | np.ndarray) – Integer(s) to convert. Either a single integers or an array of integers.

  • width (int) – Length of the bitstrings to which the integer(s) are converted. Note that the width least significant bits corresponding to integers % 2**width are returned, discarding the most significant contributions if integer > 2**(width-1)-1.

Returns:

Array of bitstrings representing the integer input. If integer is an int, the returned array has shape (width,). If integer is an array of shape S, the returned array has shape (*S, width).

Return type:

np.ndarray

Example

We may compute the binary representation of the integer 13 on five bits, for example:

>>> width = 5
>>> print(qml.math.int_to_binary(13, width=width))
[0 1 1 0 1]

This matches the output of np.binary_repr but returns a numerical array instead of a string:

>>> print(np.binary_repr(13, width=width))
01101

For an array-typed input, we obtain a new array with an additional axis in the last position, of size width:

>>> x = np.array([[7, 3], [17, 9], [2, 8]])
>>> print(x.shape)
(3, 2)
>>> bits = qml.math.int_to_binary(x, width=width)
>>> print(bits.shape)
(3, 2, 5)

The input integer can be reconstructed from the bit strings via

>>> powers_of_two = 2**np.arange(width-1, -1, -1)
>>> reconstruction = bits @ powers_of_two
>>> print(reconstruction)
[[ 7  3]
 [17  9]
 [ 2  8]]